I have such example.
function Rabbit() {
var jumps = "yes";
};
var rabbit = new Rabbit();
alert(rabbit.jumps); // undefined
alert(Rabbit.prototype.constructor); // outputs exactly the code of the function Rabbit();
I want to change the code in Rabbit() so that the var jumps becomes public. I do it this way:
Rabbit.prototype.constructor = function Rabbit() {
this.jumps = "no";
};
alert(Rabbit.prototype.constructor); // again outputs the code of function Rabbit() and with new this.jumps = "no";
var rabbit2 = new Rabbit(); // create new object with new constructor
alert(rabbit2.jumps); // but still outputs undefined
Why is it not possible to change the code in constructor function this way?
You cannot change a constructor by reassigning to
prototype.constructorWhat is happening is that
Rabbit.prototype.constructoris a pointer to the original constructor (function Rabbit(){...}), so that users of the ‘class’ can detect the constructor from an instance. Therefore, when you try to do:You’re only going to affect code that relies on
prototype.constructorto dynamically instantiate objects from instances.When you call
new X, the JS engine doesn’t referenceX.prototype.constructor, it uses theXas the constructor function andX.prototypeas the newly created object’s prototype., ignoringX.prototype.constructor.A good way to explain this is to implement the
newoperator ourselves. ( Crockford will be happy, no more new 😉Inheritance in JS
Libraries that help with JS inheritance implement inheritance and do rely on
prototype.constructorwith something in the spirit the following:You can see that in the above code, we have to fix the constructor property because it’s sometimes used to create instantiate an object when you only have an instance. but it doesn’t affect the actual constructor. See my post about JS inheritance http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
How to redefine a constructor
If you really want to redefine a constructor, just do
Note that this would not affect code that had already copied that reference, for example: