Overriding a property or function of a prototype

function Ninja(){ this.swingSword = function(){ return true; }; } // Should return false, but will be overridden Ninja.prototype.swingSword = function(){ return false; }; var ninja = new Ninja(); log( ninja.swingSword(), "Calling the instance method, not the prototype method." ); 

Now the magazine is showing me the truth. which means swingSword, which were defined in Ninja.prototype, are overridden since I can override a function or constructor property. I know that preference is given to the constructor variable, why do I need to define a function or property inside the prototype?

+7
javascript override constructor prototype
source share
2 answers

The reason for defining a function on a prototype is that it is shared between all instances. This will save you some memory, and not every instance that has its own copy of the function defined in the constructor.

Some other links that may interest you:

Javascript when to use prototypes

http://javascript.crockford.com/inheritance.html

+3
source share

This is by design. Do not set the value in the constructor if you want it to return false.

You can also make a setter method:

 function Ninja() { var swordState = true; this.swingSword = function () { return swordState; }; this.setSword = function (b) { swordState = b; }; } // Should return false, but will be overridden Ninja.prototype.swingSword = function () { return false; }; var ninja = new Ninja(); console.log(ninja.swingSword(), "Calling the instance method, not the prototype method."); ninja.setSword(false); console.log(ninja.swingSword()); // returns false 
+1
source share

All Articles