Try this syntax in console
{age:15}toString()
'[object Undefined]' // this is the return
why this happens it looks syntactically wrong so I’m not sure how the interpreter parse it ?
the object {age:15} looks like completely ignored ? is that true ?
if not ignored dose it mean it garbage as soon as it created I’m just thinking but not sure
>Solution :
{age:15}:
- Is a block. It is not an object. For more information see What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012? and in particular the explanations for
{} + []and{} + {}that deal with the same block behaviour. - It contains a label with identifier
agewhich is then followed by the expression-statement15. For more see What does the JavaScript syntax foo: mean? - It is irrelevant to the rest of the code.
The actual output here is only from toString():
console.log(toString());
With that in mind let’s examine the output: toString() is a method on the object prototype. Thus pretty much all objects have it. Including window:
console.log("toString" in window); //true
Calling just toString() means the method will be picked up from the global object – window.
Because the value of this is determined at call time and implicitly there is no object to pick it from:
A normal call would look like someObject.toString() which will set the this value to someObject. It is also equivalent to calling Object.prototype.toString.call(someObject) which will explicitly set the value of this to `someObject.
However with the entire toString() is basically equivalent to Object.prototype.toString.call(undefined) as there is nothing the method is called on.
console.log(Object.prototype.toString.call(undefined))