I was looking at the example on the MDN pages about Inheritance Revisited and thought it would be nice to have the doSomething methods actually do something. So I started out with the following code, based on the example:
function A(a) { this.varA = a };
A.prototype = { varA: null, doSomething: function() { console.log('do something with ' + this.varA) } };
function B(a, b) {
A.call(this, a);
this.varB = b;
};
B.prototype = Object.create(new A(), {
varB: { value: null, enumerable: true, configurable: true, writeable: true },
doSomething: { value: function() {
A.prototype.doSomething.apply(this, arguments);
console.log("do something with " + this.varB);
}, enumerable: true, configurable: true, writeable: true}
});
var b = new B('a', 'b');
b.doSomething();
I copy and pasted the code into the Chrome console and expected to be seeing
do something with a
do something with b
but instead I got
do something with a
do something with null
What am I overlooking here? Shouldn’t the call to “new B” result in the constructor which was defined above (function B(…)) being called? And if the constructor is called, shouldn’t b.varB have a value? How do I need to change the example so the output is as expected?
Accidentally you specified
varBas being non-writable and hence the assignmentthis.varB = bfailed (or was ignored).writeable: trueshould be spelledwritable: true(withoute). By default, properties defined using the a property descriptor are non-writable.So the whole descriptor becomes:
Since you are assigning a value inside the constructor function anyway, you don’t really have to use the descriptor though.
More information: MDN –
Object.defineProperty.