A Misconception About the JavaScript Prototype Chain and prototype

Author: Laruence I used to be somewhat confused about prototype inheritance and identifier lookup in the JavaScript prototype chain. For example, take the following code:

1
2
3
4
5
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:
Javascript object layout

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, a function object’s prototype does not take part in the prototype chain lookup. Today, under Firefox (because Firefox exposes [[prototype]] through __proto__), I found that what actually participates in identifier lookup is the function object’s __proto__,

1
2
3
4
5
function Foo() {};
var foo = new Foo();
Foo.\_\_proto\_\_.label = "laruence";
alert(Foo.label); //output: laruence
alert(foo.label);//output: undefined

And, obviously:
1
2
function Foo() {};
alert(Foo.\_\_proto\_\_ === Foo.prototype); //output: false

It also explains this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 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