Uncaught SyntaxError: Unexpected token instanceof (with Chrome Javascript console)

♀尐吖头ヾ 提交于 2019-11-27 07:48:43

问题


I am surprised that the following code when input into the Chrome js console:

{} instanceof Object

results in this error message:

Uncaught SyntaxError: Unexpected token instanceof

Can anyone please tell me why that is and how to fix it?


回答1:


The grammar for instanceof is:

RelationalExpression instanceof ShiftExpression

per ECMA-262 §11.8.

The punctuator { at the start of a statement is seen as the start of a block, so the following } closes the block and ends the statement.

The following instanceof operator is the start of the next statement, but it can't be at the start because it must be preceded by a RelationalExpression, so the parser gets a surprise.

You need to force {} to be seen as an object literal by putting something else at the start of the statement, e.g.

({}) instanceof Object



回答2:


{}, in that context, is a block, not an object literal.

You need change the context (e.g. by wrapping it in ( and )) to make it an object literal.

({}) instanceof Object;



回答3:


If you try this:

var a = {}
a instanceof Object

outputs true, which is the expected output.

However, in your case

{} instanceof Object

The above doesn't outputs true.

The latter isn't the same as the first one. In the first case, we create an object literal, while in the second case we don't. Hence you get this error.




回答4:


Try

var p = {}
p instanceof Object


来源:https://stackoverflow.com/questions/27920669/uncaught-syntaxerror-unexpected-token-instanceof-with-chrome-javascript-consol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!