简体   繁体   English

Javascript覆盖/添加原型的方法

[英]Javascript overriding/adding methods to the prototype

Basically, I want to know how/what's the difference between overriding/adding methods on instances of objects vs methods on the 'Class' instance of JS objects (yes class isn't the right word, not sure what is though). 基本上,我想知道对象实例上的覆盖/添加方法与JS对象的“类”实例上的方法之间的区别是什么/有什么区别(是的类不是正确的单词,不确定是什么)。

For example, why doesn't this work? 例如,为什么这不起作用?

Date.prototype.now= function (){
    return 23;
}

$('#foo').append(Date.now());    

And yet, this does? 然而,这样做呢?

Array.prototype.indexOf = function(){
    return 23;
}
var bar = Array();
bar[0] = "a";
$('#bar').append(bar.indexOf("a"));

http://jsfiddle.net/tad604/fMWKA/2/ http://jsfiddle.net/tad604/fMWKA/2/

now is a static method on Date . nowDate上的静态方法 It is not an instance method; 它不是实例方法; not defined on Date.prototype to begin with. Date.prototype上没有定义开始。 It is defined directly on the Date object. 它直接在Date对象上定义。 When you write 当你写作

Date.prototype.now = function () {
    return 23;
}

you are not actually overwriting the function called by Date.now() . 你实际上并没有覆盖Date.now()调用的函数。


On the other hand, indexOf for arrays is an instance method. 另一方面, 数组的indexOf是一个实例方法。 That is, it's defined on Array.prototype , so when you write 也就是说,它是在Array.prototype上定义的,所以当你写的时候

Array.prototype.indexOf = function(){
    return 23;
};

you are in fact changing the indexOf function called by 你实际上是在改变被调用的indexOf函数

var bar = [];
bar.indexOf('a');

See the difference? 看到不同? http://jsfiddle.net/mattball/7qVQy/ http://jsfiddle.net/mattball/7qVQy/


I recommend reading about the JavaScript prototype lookup chain , which should clarify some of your confusion. 我建议阅读有关JavaScript原型查找链的内容 ,这应该澄清一些您的困惑。

You are calling the static Date object and not it's constructor. 您正在调用静态Date对象而不是它的构造函数。 from MDN , 来自MDN

Invoking JavaScript Date in a non-constructor context (ie, without the new operator) will return a string representing the current time. 在非构造函数上下文中调用JavaScript Date(即,没有new运算符)将返回表示当前时间的字符串。

Try this instead http://jsfiddle.net/fMWKA/4/ 试试这个http://jsfiddle.net/fMWKA/4/

true what MДΓΓ БДLL said. 真正的MДΓΓБДLL说。 Just for educational purposes, you could create a new instance of Date and therefore use the method declared in the prototype. 仅出于教育目的,您可以创建Date的新实例,因此使用原型中声明的方法。

Date.prototype.now = function() {
  return 23;
}
Date = new Date();
document.write(Date.now());

http://jsfiddle.net/n9h4y/ http://jsfiddle.net/n9h4y/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM