Search code examples
javascriptfunctionecmascript-6prototypal-inheritance

What is the prototype chain for a function constructor?


I have been learning about the prototype chain from a tutorial and am confused by the prototype chain for a function constructor.

Here is my constructor function with a prototype and a new instance:

let Fun2 = function(name) {
    this.name = name
}

Fun2.prototype.who = () => console.log('who')

const name = new Fun2('bill')

then as I expect, the __proto__ property of the name instance is the Fun2 prototype, however the prototype property of Fun2 points to the Object prototype:

name.__proto__.__proto__
{constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}

I also learned that a functions prototype chain goes up to a general function.prototype (the same as an array has an array.prototype), since Fun2 is a function, why doesn't it point to the function.prototype and then point to the Object.prototype, I don't understand why it is skipping this step, can someone clarify this please.


Solution

  • The thing that can be confusing is that the prototype property (of a constructor) gives the prototype for objects that the function will construct, while the __proto__ property of the constructor refers to the prototype used for creating the constructor. These are unrelated prototypes: the constructor has a prototype chain that has nothing to do with the prototype chain of an object that is constructed with that constructor.

    why doesn't it point to the function.prototype and then point to the Object.prototype

    It does that. Object.getPrototypeOf(Function.prototype) is Object.prototype.

    Look at these results:

    const Fun2 = function(name) {}
    const name = new Fun2('bill');
    
    console.log(
        "Test prototype chain of the constructed object:",
        Object.getPrototypeOf(name) === Fun2.prototype, // true
    //                                       ↓
                  Object.getPrototypeOf(Fun2.prototype) === Object.prototype, // true
    );
    
    console.log(
        "Test prototype chain of the constructor:",
        Object.getPrototypeOf(Fun2) === Function.prototype, // true
    //                                       ↓
                  Object.getPrototypeOf(Function.prototype) === Object.prototype, // true
    );

    See also How does JavaScript .prototype work? and, if you wish, my answer in that collection of answers.