覆盖原型属性或功能

Moh*_*han 8 javascript constructor overriding 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." );
Run Code Online (Sandbox Code Playgroud)

现在日志显示我是真的.这意味着在Ninja.prototype中定义的swingSword已被覆盖,因此如何覆盖构造函数或属性.我知道首选的是构造函数变量然后为什么需要在原型中定义一个函数或属性?

Ste*_*ser 3

在原型上定义函数的原因是它可以在所有实例之间共享。这将为您节省一些内存,而不是每个实例都有自己的构造函数中定义的函数副本。

您可能感兴趣的其他一些参考资料:

Javascript 何时使用原型

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