Bryan Grace
Bryan Grace

Reputation: 1882

JavaScript Inheritance, Resetting the prototype constructor?

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?

Upvotes: 0

Views: 104

Answers (1)

Bryan Grace
Bryan Grace

Reputation: 1882

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.

Upvotes: 1

Related Questions