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();
How do I retrieve the last reference (indicated by ???) without knowing the name of the constructor?
For instance, say I had an object which inherits from a chain of prototypes. Can I know which prototype is used when I call a method on it?
Both seem theoretically possible, but I can’t find any way that works without more than constant number of assignment statements (if I have many such functions).
The prototype of each function has a reference back to the function via the
constructorproperty [MDN]. So you can get the constructor function viaGetting the prototype is a bit trickier. In browsers supporting ECMAScript 5, you can use
Object.getPrototypeOf[MDN]:In older browser it might be possible to get it via the non-standard
__proto__[MDN] property:Yes, if the browser supports ES5. Then you have to repeatedly call
Object.getPrototypeOf()until you find the object with that property. For example: