The following code is available:
function Rabbit () {var jumps = "yes";}; var rabbit = new Rabbit (); alert (rabbit.jumps); Undefinedalert (Rabbit.prototype.constructor); Outputs exactly the code of the function Rabbit ();
Change to this:
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 Constructoralert (Rabbit2.jumps); But still outputs undefined
Why is jumps still undefined?
That's because:
Rabbit.prototype.constructor is simply a reference to the original constructor, which is used to detect its constructor when the class is instantiated. So, if you try:
Rabbit.prototype.constructor = function Rabbit () {this.jumps = "no";};
You just broke the reference on the prototype object to the original object constructor. So you can't change the original constructor.
Why can't I modify the constructor function from prototype