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).
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"));
nowis a static method onDate. It is not an instance method; not defined onDate.prototypeto begin with. It is defined directly on theDateobject. When you writeyou are not actually overwriting the function called by
Date.now().On the other hand,
indexOffor arrays is an instance method. That is, it’s defined onArray.prototype, so when you writeyou are in fact changing the
indexOffunction called bySee the difference? http://jsfiddle.net/mattball/7qVQy/
I recommend reading about the JavaScript prototype lookup chain, which should clarify some of your confusion.