Javascript Object prototype properties

Published in Code on Apr 9, 2015


// can be used on all native Javascript datatypes
// returns whichever primitive type is associated with/assigned to the object 
// can be overridden to return an alternative value

To override the .valueOf() prototype property:

Object.prototype.valueOf() = function() {...}


// returns the value of the object, cast to a string.
// if object is array, will return "string-ify" and concatenate the all the contents, delimited by commas without any whitespace. Overriding the .toString() property in the Array prototype is often desirable. 

To override the .toString() prototype property

Object.prototype.toString() = function() {...}


// returns the constructor function of the object.
Fx, return:

function (category, area) {
    this.category = category;
    this.area = area;    


// returns the prototype object associated with the constructor
Fx, returns:

Object {valueOf: function, toString: function }

or, shorthand


*Note: If the prototype property is defined for a class, then it will always be a property of the constructor object