Home > Software design >  What is the prototype chain for a function constructor?
What is the prototype chain for a function constructor?

Time:12-06

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.

CodePudding user response:

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 enter image description here

function myFunction() {}

myFunction.prototype.Test = function () {};

console.log(myFunction.__proto__ === Function.prototype); //True

console.log(myFunction.constructor === Function.prototype.constructor); //True

console.log(myFunction.prototype.constructor === myFunction); //True

In case if you are creating the object using the new operator

let obj1 = new myFunction();

console.log(obj1.__proto__ === myFunction.prototype); //True

let obj2 = Object.create(myFunction.prototype);

console.log(obj2.__proto__ === myFunction.prototype); //True
  • Related