2

所以我得到了这段小代码,不要打扰它的实现方式。

function A() {}

A.prototype = {
    nw: function(t) {
        return new t(A);
    }
}

如果通过原型继承的孩子(例如 B)将调用函数 nw,并且我希望它返回 new t(B),我必须用什么替换 new t(A) 中的 A 才能传递正确的参数?

像'return new t(this)'这样的东西?

B.nw(C) 将返回新的 C(B)。

4

3 回答 3

0

如果我理解正确,这就是你想要的:

function A() {}

A.__proto__ = {
    log: function(t) {
        return new t(this);
    }
}

如果您运行以下代码

A.log(function(obj){
    console.log(obj);
});

它将记录 A

于 2012-06-18T11:46:06.843 回答
0

您可以实现一个简单的继承机制:

var Class = function( parent ){
   var f = function(){};

   if( typeof parent == 'function' ){
      f.prototype = new parent;  
   }else if( parent) {
       f.prototype = parent;  
   }

   f.prototype.__parent = parent;  // :)
   f.prototype.__root = ( parent &&  parent.prototype && parent.prototype.__root) || parent || f; // :)
   return f
};

现在:

   var A = Class(),
       B = Class(A),
       C = Class(B),

       objA = new A,
       objB = new B,
       objC = new C;

objC.__parent == B; // true;
objB.__parent == A; // true

(objC.__root == objB.__root) && ( objA.__root == A ); // true;

但是,您可以为根对象指定原型(您的情况):

   var A = Class({ 
             nw: function( t ) {                  
                    // What you like here? :)    

                    return new t( this.__parent ); 
                    //return new t( this.constructor );  
                    //return new t( this.__root );
             } 
           });
于 2012-06-19T07:26:37.097 回答
0

呃,其他答案看起来很复杂。看起来你只是想要:

function A() {}

A.prototype = {
    constructor: A,

    nw: function(t) {
        return new t( this.constructor );
    }
}
于 2012-06-19T12:44:57.903 回答