Created
October 10, 2017 11:33
-
-
Save parwatcodes/94071d1ba6df156d5e3b2436b250c13b to your computer and use it in GitHub Desktop.
changing a constructor function definition using `functionaName.prototype.constructor`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Rabbit() { | |
this.jumps = "yes"; | |
}; | |
var rabbit = new Rabbit(); | |
console.log(rabbit.jumps); | |
// Rabbit.prototype.constructor is a pointer to the original constructor `function Rabbit(){..})` so that the users of the class can detect the constructor from an instance | |
console.log(Rabbit.prototype.constructor); | |
// outputs exactly the code of the function Rabbit() | |
function ChangeConstructor() { | |
this.jumps = 'no' | |
} | |
// Rabbit.prototype.constructor = function Rabbit() { | |
// this.jumps = 'no' | |
// } | |
Rabbit.prototype.constructor = ChangeConstructor | |
console.log(rabbit.jumps) | |
console.log(Rabbit.prototype.constructor) | |
var a = new Rabbit() | |
console.log(a.jumps) | |
// Therefore, when you try to do | |
Rabbit.prototype.constructor = function Rabbit() { | |
this.jumps = "no"; | |
}; | |
// You're just breaking the link between the original constructor and the reference to it on the prototype. So the answer is no, you cannot change a constructor by reassigning to prototype.constructor | |
console.log(Rabbit.prototype.constructor) | |
var rabbit2 = new Rabbit(); | |
console.log(rabbit2.jumps) | |
// How to redefine a constructor if you really want to redefine a constructor, just do | |
var oldProto = Rabbit.prototype; | |
// keeping Rabbit prototype in oldProto variable | |
Rabbit = function() { // creating a new constructor function with a new definition | |
this.jumps = 'no' | |
}; | |
Rabbit.prototype = oldProto; // assigning all the prototypes to the new defined Rabbit constructor function prototype | |
var nn = new Rabbit() | |
console.log(nn.jumps) |
Author
parwatcodes
commented
Oct 10, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment