JavaScript

Object.prototype.toString.call()?

This seems to be a standardised way to tell the type of a javascript object. Why?

First thing to realise is that Object.prototype.toString, Number.prototype.toString, Function.prototype.toString, String.prototype.toString and Array.prototype.toString are all different things

Object.prototype.toString

var o = new Object();
o.toString(); 
// [object Object]

Function.prototype.toString: Returns a string representing the source code of the function.

var fn = function(x) {return x;}
fn.toString()
// "function (x){return x;}"

String.prototype.toString

var x = new String("Hi"); 
x.toString()
// "Hi"

Array.prototype.toString

arr = ['a', 'b'];
x = arr.toString()
y = arr.join(',')
// The above two expressions are equivalent, both return:
// "a,b"

Number.prototype.toString: The only one that takes parameter, which takes an integer between 2 and 36.

var count = 10;

console.log(count.toString()); // displays '10'
console.log((17).toString()); // displays '17'

var x = 6;

console.log(x.toString(2)); // displays '110'
console.log((254).toString(16)); // displays 'fe'

console.log((-10).toString(2)); // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'

Object.prototype.toString And Its Uses

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString()method is inherited by every object descended from Object. If this method is not overridden in a custom object,toString() returns “[object type]”, where type is the object type.

So in order to tell arrays from pure objects, Object.prototype.toString() is the one we need:

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
Standard