In Javascript Inheritance Via B.prototype = New A() Why Does One Need To Set B.prototype.constructor = B?
Also is this a good inheritance pattern? I never saw it being discussed in JavaScript inheritance tutorials, yet sometimes being used in actual code. Can you point out drawbacks an
Solution 1:
Because the constructor is now pointing to the constructor(prototype property) of "A" so we want it to point it to B()
B.prototype.constructor is an pointer to the original constructor when we change the prototype of B (B.prototype = new A()
) the B.prototype.constructor loses the reference to actual A() and refers to/points to B(). Note new A() will still call default constructor.
Here only purpose to change it back to B() (B.prototype.constructor=B
) can be that when in future for some purpose calling the constructor with prototype like B.prototype.constructor()
or B.prototype.constructor.call()
it doesn't point to A()
Example
functionA(){
console.log("A")
}
functionB(){
console.log("B")
}
B.prototype = Object.create(A.prototype);
newB() // Still console.logs "B"
B.prototype.constructor() // console.logs "A"
Post a Comment for "In Javascript Inheritance Via B.prototype = New A() Why Does One Need To Set B.prototype.constructor = B?"