Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override toString() Javascript On a Single Array Object

I have the following:

var version = [0,3,0];

// Override the version toString method.
version.__proto__.toString = function() {
    return this.join('.');
};

Which does the following

version.toString => '0.3.0'

JSlint moans that __proto__ is a reserved name - which is correct.

I assume I am overloading incorrectly.

I do not want to

Array.prototype.toString

as that'll override all arrays to replace , with .?

like image 546
Matt Clarkson Avatar asked Dec 05 '22 19:12

Matt Clarkson


1 Answers

Just set the method on the array directly:

var version = [0,3,0];

// Override the version toString method.
version.toString = function() {
    return this.join('.');
};
like image 172
Matt Ball Avatar answered Dec 27 '22 18:12

Matt Ball