Considering the simplistic scenario:
function Base() {} function Child() {} Child.prototype = new Base;
I wonder why would an instance of Child have constructor property set to Base and not to Child?
Considering the simplistic scenario:
function Base() {} function Child() {} Child.prototype = new Base;
I wonder why would an instance of Child have constructor property set to Base and not to Child?
It's all tied to how inheritance works in JavaScript. Check this link for a detailed explanation (basically, constructor
is just another property of the prototype).
Edit: Also, if you want 'real' prototypical inheritance, you have to use some sort of clone function, eg
function clone(obj) {
if(typeof obj !== 'undefined') {
arguments.callee.prototype = Object(obj);
return new arguments.callee;
}
}
Then, you can do things like this
function Base() {}
function Sub() {}
Sub.prototype = clone(Base.prototype);
var obj = new Sub;
and you'll still get true
two times on
document.writeln(obj instanceof Sub);
document.writeln(obj instanceof Base);
The difference to your solution is that Base()
won't be called and Sub.prototype
will only inherit the properties of Base.prototype
- and not the ones set in the constructor.
function Base() {}
//Base.prototype.constructor === Base
function Child() {}
//Child.prototype.constructor === Child;
var b = new Base;
//b.constructor = Base;
Child.prototype = b;
//Child.prototype.constructor === Base
basically, any property of the prototype becomes a property of the instance, including "constructor"
when you reassign the whole prototype property to a new object, you're replacing the old constructor property with the new one.
if you don't want this to happen, you have to assign properties to the prototype object one by one, instead of assigning the whole prototype property to a new object at once. Or replace the old constructor property afterward.
Much better idea: don't rely on the constructor property for anything important.