javascript 覆盖原型属性或函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22060748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:19:19  来源:igfitidea点击:

overriding prototype property or function

javascriptconstructoroverridingprototype

提问by Mohammad Faizan khan

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??

现在记录显示我是真的。这意味着在 Ninja.prototype 中定义的 swingSword 已被覆盖,所以我如何覆盖构造函数或属性。?我知道优先考虑构造函数变量那为什么需要在原型中定义函数或属性?

采纳答案by 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

Javascript 何时使用原型

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

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

回答by Andrew Templeton

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

这是设计使然。如果您希望它返回 false,请不要在构造函数中设置该值。

You can also make a setter method:

您还可以创建一个 setter 方法:

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