JavaScript
x
14
14
1
function Ninja(){
2
this.swingSword = function(){
3
return true;
4
};
5
}
6
7
// Should return false, but will be overridden
8
Ninja.prototype.swingSword = function(){
9
return false;
10
};
11
12
var ninja = new Ninja();
13
log( ninja.swingSword(), "Calling the instance method, not the prototype method." );
14
now log showing me true. which means swingSword that were defined in Ninja.prototype has overridden so how can i override the constructor function or property.?? i know that preference is given to constructor variable then why need to define a function or property inside prototype??
Advertisement
Answer
The reason to define a function on the prototype is so that it is shared between all instances. This will save you some memory rather than each instance having its own copy of a function defined in the constructor.
Some other references you might be interested in: