admin管理员组文章数量:1405507
When object literal calls toString()
method like {}.toString()
will cause syntax error, but when array literal call toString()
it is OK. And when I assign the object literal to a variable, then when it call the toString()
method will be OK. Why? For example:
var o = {};
o.toString(); // OK
{}.toString();
// > Uncaught SyntaxError: Unexpected token .
[1, 2, 3].toString(); // OK
Thanks!
When object literal calls toString()
method like {}.toString()
will cause syntax error, but when array literal call toString()
it is OK. And when I assign the object literal to a variable, then when it call the toString()
method will be OK. Why? For example:
var o = {};
o.toString(); // OK
{}.toString();
// > Uncaught SyntaxError: Unexpected token .
[1, 2, 3].toString(); // OK
Thanks!
Share edited Jun 8, 2017 at 15:03 zhenguoli asked May 29, 2017 at 10:58 zhenguolizhenguoli 2,3081 gold badge16 silver badges32 bronze badges 01 Answer
Reset to default 13It's because {}
is seen as a valid block first, instead of a literal in that context.
In simple terms - consider that line is interpreted from left to right, encounters {
and therefore expects that a block has started. When the block ends, it encounters .
and that identifier is not allowed there.
If you were to use ({}).toString()
that will work.
This is because the line starts with (
and therefore expects an expression, it correctly identifies the {}
as an expression which is evaluated to an empty object and therefore '.toString()` is allowed.
If {}
is used in another context - e.g. in your example o = {}
this is correctly interpreted as an empty object because is's on the right-hand side of an assignment (after =
).
Note that in ES6 there is a similar but more mon/practical situation where understanding this is important - when returning objects in one-liner arrow functions, e.g.
[1,2,3,4].map(val => { v: val, isOdd: v % 2 === 1 }) // ERROR
[1,2,3,4].map(val => ({ v: val, isOdd: v % 2 === 1 })) // OK
本文标签: javascriptwhy can39t object literal call toString() method like toString() cause errorStack Overflow
版权声明:本文标题:javascript - why can't object literal call toString() method like {}.toString() cause error? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744922887a2632406.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论