2012-06-18 113 views
2

所以我得到了這個小小的代碼,不要打擾它的實現方式。JavaScript對象名稱,調用函數?

function A() {} 

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

如果一個孩子(例如B)通過原型繼承會調用該函數NW,我想它返回新的T(B),我有什麼要更換新的T(A)與傳遞正確的參數?

像'return new t(this)'? (C)將返回新的C(B)。

+0

你想傳遞't'函數? 當前對象,父對象或根對象的實例? – abuduba

+0

父對象:) – Igor

+0

您可以嘗試'this.prototype.constructor',這是我們常規放置構造方法的地方。現在分配給這樣的原型,我懷疑它會起作用,你應該使用一個很像coffescript生成的設計。 – Eric

回答

0

呃,其他的答案只是眼神複雜。它看起來像你只是想:

function A() {} 

A.prototype = { 
    constructor: A, 

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

如果我理解這個正確的,這是你想要什麼:

function A() {} 

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

如果您運行下面的代碼

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

它會記錄一個

+0

'__proto__'不是標準的。 – Ashe

+0

既不是原型 – Luka

+0

是的。參見[ECMA-262,§4.2.1Objects](http://es5.github.com/#x4.2.1):「*每個構造函數都有一個名爲」'prototype「的屬性,用於實現*基於原型的繼承*和*共享屬性。「注意'__proto__'從未被提及過。 – Ashe

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); 
      } 
      });