- URL: https://www.laruence.com/en/2010/05/13/1462.html
- Please include attribution when republishing.
I used to be confused about prototype inheritance versus identifier lookup in the JavaScript prototype chain. Take this code:
function Foo() {};
var foo = new Foo();
Foo.prototype.label = "laruence";
alert(foo.label); //output: laruence
alert(Foo.label);//output: undefined
Today I came across this diagram:

Also, over at Javascript Object Hierarchy I read:
The prototype is only used for properties inherited by objects/instances created by that function. The function itself does not use the associated prototype.
In other words, the prototype of a function object plays no part in prototype chain lookup.
Today, under firefox (which exposes [[prototype]] through __proto__), I found that what actually takes part in identifier lookup is the __proto__ of the function object:
function Foo() {};
var foo = new Foo();
Foo.__proto__.label = "laruence";
alert(Foo.label); //output: laruence
alert(foo.label);//output: undefined
And, obviously:
function Foo() {};
alert(Foo.__proto__ === Foo.prototype); //output: false
It also explains this:
alert(Object.forEach); // undefined
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
alert(Object.forEach);
alert(Function.forEach);
alert(Object.forEach === Function.forEach); // true
Be First to Comment