I’m actively learning javascript, and I came across the following statement:
Object.prototype.toString.call([]);
And I don’t know what it means or what it does.
I have a vague understanding of .call, in that it allows you to call a method in the context of a different object (I think), but I am having a hard time understanding what role the .call() function is playing in the above statement. So I was wondering if anyone could explain what .call() is doing here?
Thanks!!
The
callmethod sets thethisvalue of the invoked function to the object passed as first argument, in your example, you are executing theObject.prototype.toStringmethod on an Array object.Array objects, have their own
toStringmethod (Array.prototype.toString) that shadows the one fromObject.prototype, if you call[].toString();the method on theArray.prototypewill be invoked.For example:
Another example:
In the above example, we use the Alice’s
getNamemethod on the Bob’s object, thethisvalue points tobob, so the method works just as if it were defined on the second object.Now let’s talk about the
Object.prototype.toStringmethod. All native objects in JavaScript contain an internal property called[[Class]]this property contains a string value that represents the specification defined classification of an object, the possible values for native objects are:"Object""Array""Function""Date""RegExp""String""Number""Boolean""Error"for error objects such as instances ofReferenceError,TypeError,SyntaxError,Error, etc"Math"for the globalMathobject"JSON"for the global JSON object defined on the ECMAScript 5th Ed. spec."Arguments"for theargumentsobject (also introduced on the ES5 spec.)"null"(introduced just a couple of days ago in the ES5 errata)"undefined"As I’ve said before that property is internal, there is no way to change it, the specification doesn’t provide any operator or built-in function to do it, and the only way you can access its value is through the
Object.prototype.toStringmethod.This method returns a string formed by:
Only for expository purposes because
[[Class]]cannot be accessed directly.For example:
This is really useful to detect the kind of an object in a safe way, for detecting array objects, it’s the most widely used technique:
It might be tempting to use the
instanceofoperator, but that way will lead to problems if you work on cross-frame environments, because an array object created on one frame, will not beinstanceoftheArrayconstructor of another.The above method will work without any problems, because the object will contain the value of its
[[Class]]internal property intact.See also:
instanceofconsidered harmful (or how to write a robustisArray)Object.prototype.toString