0

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?

1
  • 1
    In both cases you are overriding B.prototype with a new object. So the constructor is gone (you have to reset it). You can add a "constructor" property to the object literal that you are assigning to B.prototype like: B.prototype = { constructor: B, write: ... };. Commented Dec 8, 2017 at 21:24

1 Answer 1

1

Thanks Ibrahim, for pointing out, that in both cases I was overriding B.prototype.

In light of this, it seems that:

1.

B.prototype = Object.assign(B.prototype, A.prototype, {
    write: function() {
        this.fn();
    }
});

2.

B.prototype = Object.assign(B.prototype, {
    write: function() {
        console.log('good')
    }
});

Should leave the original prototype constructor intact.

Sign up to request clarification or add additional context in comments.

1 Comment

Object.assign is defined in the ES2015 spec, if the intention is to use in older browsers you will need a polyfill. Also, why not attach the functions directly to the original prototype? (B.prototype.write = fun...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.