Here's a basic example of instance inheritance:
function A() {
this.props = {
a: 'a',
b: 'b'
}
}
A.prototype = {
fn: function() {
console.log(this.props);
}
}
function B() {
A.call(this);
}
B.prototype = Object.assign(A.prototype, {
write: function() {
this.fn();
}
});
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() { A.call(this); }
var b = new B();
And here's an example of the same functions without inheritance:
function A() {
this.props = {
a: 'a',
b: 'b'
}
}
A.prototype = {
fn: function() {
console.log(this.props);
}
}
function B() {
}
B.prototype = {
write: function() {
console.log('good')
}
}
/*
I don't think anyone advocates setting the prototype constructor
as the Function to which it belongs in this case.
*/
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() {}
var b = new B();
As you can see, in both cases, before the line:
B.prototype.constructor = B;
The prototype constructor is the native Object constructor and afterward it is the Object/Function which the prototypes were declared on.
Is the line in question necessary for older browsers, was it necessary to combat some popular bad techniques, or am I not doing prototypal inheritance correctly?
B.prototypewith a new object. So theconstructoris gone (you have to reset it). You can add a"constructor"property to the object literal that you are assigning toB.prototypelike:B.prototype = { constructor: B, write: ... };.