2012-07-19 90 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