overriding prototype property or function
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 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??
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:
Javascript when to use prototypes
http://javascript.crockford.com/inheritance.html
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
链接地址: http://www.djcxy.com/p/77720.html
上一篇: 无法按重复列排序
下一篇: 覆盖原型属性或功能