设定 subFn 的默认构造器 
跟java里的 无参构造函数似的

解决方案 »

  1.   

    能说说怎么用吗
    运行出错啊
    superFn is not a constructor
      

  2.   

    知道怎么用了
    lz看看这两个例子就知道了
    function Extend(subFn, superFn){ 
        subFn.prototype = new superFn() 
    subFn.prototype.constructor = subFn 
    }function f1(){}
    function f2(){}alert((new f2()).constructor)Extend(f2, f1)alert((new f2()).constructor)
    function Extend(subFn, superFn){ 
        subFn.prototype = new superFn() 
    //subFn.prototype.constructor = subFn 
    }function f1(){}
    function f2(){}alert((new f2()).constructor)Extend(f2, f1)alert((new f2()).constructor)
      

  3.   

    我刚运行了下,发现去掉那句话:(new f2()).constructor是f1(){}
    我刚开始理解是new f2()取的是f1的构造函数,但是我断点执行了一下,执行的还是f2中的构造函数,所以我还是不明白为什么.是不是浏览器的关系
      

  4.   


    function Extend(subFn, superFn){ 
        subFn.prototype = new superFn()   //此时subFn.prototype被重置为new superFn,原来subFn.prototype.constructor也没了
        subFn.prototype.constructor = subFn       //恢复原来subFn.prototype.constructor
    }function f1(){}    //此时f1.prototype.constructor = f1
    function f2(){}    //此时f1.prototype.constructor = f1alert((new f2()).constructor)Extend(f2, f1)alert((new f2()).constructor)
    function Extend(subFn, superFn){ 
        subFn.prototype = new superFn()   //此时subFn.prototype被重置为new superFn,原来subFn.prototype.constructor也没了
         //subFn.prototype.constructor = subFn       //恢复原来subFn.prototype.constructor
    }function f1(){}    //此时f1.prototype.constructor = f1
    function f2(){}    //此时f1.prototype.constructor = f1alert((new f2()).constructor)Extend(f2, f1)alert((new f2()).constructor)    //(new f2).constructor将沿着prototype链找到f1.prototype.constructor,也即f1本身
      

  5.   

    可以把constructor作为一个普通的属性,和内部的构造函数没有必然联系
    try this onefunction ClassA(){
    this.Str = "The String From A";
    }function ClassB(){
    this.Str = "The String From B";
    }ClassA.prototype.constructor = ClassB;var ins = new ClassA();alert(ins.constructor);
    alert(ins instanceof ClassA)
    alert(ins instanceof ClassB);
    alert(ins.Str);