Javascript调用函数的对象名称?

时间:2012-06-18 10:33:33

标签: javascript object reference parent

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

function A() {}

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

如果通过原型继承的子(例如B)将调用函数nw,并且我希望它返回新的t(B),那么我必须在新t(A)中替换A以传递右边的参数β

像'return new t(this)'?

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

3 个答案:

答案 0 :(得分:0)

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

function A() {}

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

如果您运行以下代码

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

它会记录A

答案 1 :(得分: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 );
             } 
           });

答案 2 :(得分:0)

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

function A() {}

A.prototype = {
    constructor: A,

    nw: function(t) {
        return new t( this.constructor );
    }
}