Home >Web Front-end >JS Tutorial >Why Doesn't JavaScript's `constructor` Property Update During Prototypal Inheritance?
JavaScript Inheritance: Understanding the Constructor Property
Question:
Consider the code:
function a() {} function b() {} function c() {} b.prototype = new a(); c.prototype = new b(); console.log((new a()).constructor); //a() console.log((new b()).constructor); //a() console.log((new c()).constructor); //a()
Why isn't the constructor property updated for b and c, despite setting their prototype to inherit from a?
Answer:
To understand this, let's embark on a conceptual journey:
Now, the question arises: why isn't the constructor property defined on the instance object itself? Consider the following example:
function defclass(prototype) { var constructor = prototype.constructor; constructor.prototype = prototype; return constructor; } var Square = defclass({ constructor: function (side) { this.side = side; }, area: function () { return this.side * this.side; } }); var square = new Square(10); console.log(square.area()); // 100
In this example, the constructor property is a method of the prototype like any other. However, it is used specifically to initialize instances of the prototype.
Defining the constructor property on the prototype provides several advantages:
Inheritance and the Constructor Property
In the case of inheritance, the prototype property of the derived constructor is set to an instance of the base constructor. Consequently, the internal [[proto]] property of the derived constructor instance also points to the base constructor's prototype. This results in the derived constructor instance's constructor property pointing to the base constructor.
The instanceof Operator
The instanceof operator operates on an instance object and a constructor function. Contrary to popular belief, it does not rely on the constructor property of the instance. Instead, it traverses the prototype chain of the instance and checks if its internal [[proto]] property matches the prototype property of the constructor. A match returns true, while an end to the prototype chain returns false.
The above is the detailed content of Why Doesn't JavaScript's `constructor` Property Update During Prototypal Inheritance?. For more information, please follow other related articles on the PHP Chinese website!