覆盖原型属性或函数 [英] overriding prototype property or function

查看:144
本文介绍了覆盖原型属性或函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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." );

现在日志显示为true。这意味着在Ninja.prototype中定义的swingSword已经覆盖,因此我如何覆盖构造函数或属性。
i知道偏好是给构造函数变量,那么为什么需要在原型中定义一个函数或属性

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何时使用原型

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

这篇关于覆盖原型属性或函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆