What is the difference between Array.prototype.reverse and Array.reverse
in Javascript?
The question I have deals with an application of adding a new method to
the existing String constructor. In Object Oriented Program for Javascript
by Stoyan Stefanov, there is an example of using the Array constructor's
.reverse() method to create one for the String constructor. Here is the
example:
String.prototype.reverse = function() {
return Array.prototype.reverse.apply(this.split('')).join('');
}
I thought the .reverse() method of Array belonged directly to the object
of Array. In fact, when I try to do the second bit of code with this
statement:,
String.prototype.reverse = function() {
return Array.reverse.apply(this.split('')).join(''); //WITHOUT the
.prototype
}
var rev = "karunesh".reverse(); //applying the code here
I get an error in the Firebug Console stating: "TypeError: missing
argument 0 when calling function Array.reverse". That does not make any
sense to me.
And of course, if I add back in the .prototype, it works perfectly fine.
Also, if is the case that I have to call upon prototype to access the
.reverse() method from the Array object, then is it the case that I have
to do that for any built-in object in Javascript?
Thanks for the help in advance!
No comments:
Post a Comment