Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript overriding/adding methods to the prototype

Tags:

javascript

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

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

like image 553
tad604 Avatar asked May 29 '26 00:05

tad604


1 Answers

now is a static method on Date. It is not an instance method; not defined on Date.prototype to begin with. It is defined directly on the Date object. When you write

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

you are not actually overwriting the function called by Date.now().


On the other hand, indexOf for arrays is an instance method. That is, it's defined on Array.prototype, so when you write

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

you are in fact changing the indexOf function called by

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

See the difference? http://jsfiddle.net/mattball/7qVQy/


I recommend reading about the JavaScript prototype lookup chain, which should clarify some of your confusion.

like image 121
Matt Ball Avatar answered May 31 '26 14:05

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!