overriding prototype property or function

北城余情 提交于 2019-12-05 03:23:39
Stephen Kaiser

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

Andrew Templeton

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!