2012-07-19 92 views
1
Constructor1=function(){}; 
Constructor1.prototype.function1=function this_function() 
{ 
    // Suppose this function was called by the lines after this code block 
    // this_function - this function 
    // this - the object that this function was called from, i.e. object1 
    // ??? - the prototype that this function is in, i.e. Constructor1.prototype 
} 
Constructor2=function(){}; 
Constructor2.prototype=Object.create(Constructor1.prototype); 
Constructor2.prototype.constructor=Constructor2; 
object1=new Constructor2(); 
object1.function1(); 

如何在不知道構造函數名稱的情況下檢索最後一個引用(用???表示)?例如,假設我有一個從原型鏈繼承的對象。當我調用一個方法時,我可以知道使用哪個原型嗎?JavaScript函數可以引用原型鏈上的原型嗎?

這兩個看起來理論上可能,但我找不到任何工作沒有超過常數的賦值語句(如果我有很多這樣的功能)。

回答

0

每個函數的原型都通過constructor property [MDN]有一個參考。所以你可以通過構造函數獲得

var Constr = this.constructor; 

獲取原型有點棘手。在瀏覽器支持的ECMAScript 5,你可以使用Object.getPrototypeOf[MDN]

var proto = Object.getPrototypeOf(this); 

在較早的瀏覽器,它可能可以通過非標準__proto__[MDN]屬性來獲取它:

var proto = this.__proto__; 

我可以知道當我調用一個方法時使用哪個原型嗎?

是的,如果瀏覽器支持ES5。然後,您必須重複呼叫Object.getPrototypeOf(),直到找到具有該屬性的對象。例如:

function get_prototype_containing(object, property) { 
    do { 
     if(object.hasOwnProperty(property)) { 
      break; 
     } 
     object = Object.getPrototypeOf(object); 
    } 
    while(object.constructor !== window.Object); 

    // `object` is the prototype that contains `property` 
    return object; 
} 

// somewhere else 
var proto = get_prototype_containing(this, 'function1'); 
+0

看到我上面的編輯...我澄清了一點 – user1537366 2012-07-19 10:47:32

+0

@ user1537366:看到我的更新。 – 2012-07-19 10:58:56

+0

嗯,這有點像做瀏覽器已經做的事情,所以我很驚訝沒有更好的辦法......另外,你將如何找出我最初想要的是什麼?是這樣嗎? 'get_prototype_containing(this,this_function.toString()。substring(「function」.length,this_function.toString()。indexOf(「(」)))? – user1537366 2012-07-19 11:32:40