本文介绍了javascript 意外令牌.使用 `{}.toString()`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是为什么以下不正确

My question is why following is incorrect

function hello () {
    {}.toString();//Unexpected token .
}

但使用 return 正确:

function hello () {
    return {}.toString();
}

不知道解析器如何处理不正确的版本,{} 是否被视为 BlockStatement?如果是,那为什么?

No idea how parser works for the incorrect version, is {} treated as BlockStatement? If yes, then why?

感谢详细解释

推荐答案

没错.

...为什么?

纯粹是因为语法就是这样设计的.{ 当解析器需要一个语句(它在那里),所以语法说它开始一个块.因此,{ 开始一个块,} 结束它,并且 . 没有意义,因为解析器期待一个语句(或关闭函数体的 }).

Purely because that's the way the grammar is designed. { would be ambiguous between starting a block and starting an object initializer when the parser is expecting a statement (which it is there), so the grammar says it starts a block. Thus, { starts a block, } ends it, and the . doesn't make sense because the parser is expecting a statement (or a closing } for the function body).

但是在第二个例子中.因为 {return 之后,解析器是 期待一个表达式(不是一个语句),所以 { 启动一个对象初始值设定项.

But in the second example. because the { is after return, the parser is expecting an expression (not a statement), so { starts an object initializer.

任何将解析器置于期望表达式的状态的任何事情都会使其将 { 视为对象初始值设定项的开始.在这种情况下通常使用括号:

Anything to put the parser in a state where it's expecting an expression will make it treat that { as the beginning of an object initializer. Parentheses are commonly used in that case:

function hello() {
    ({}).toString();
}

当然,该函数没有做任何事情,因为您没有使用 toString...

Of course, that function doesn't do anything, because you're not using the result of toString...

这篇关于javascript 意外令牌.使用 `{}.toString()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:52