直接访问空对象{}上的属性时的语法错误 [英] Syntax Error when directly access attribute on empty object {}
问题描述
> "[object Number]" === Object.prototype.toString.call(1) // #1
< true
> "[object Number]" === {}.toString.call(1) // #2
< true
> {}.toString.call(1) === "[object Number]" // #3
< SyntaxError: Unexpected token '.'
> ({}).toString.call(1) === "[object Number]" // #4
< true
> {}.toString.call(1) // #5
< SyntaxError: Unexpected token '.'
> !{}.toString.call(1) // #6
< false
> test = {}.toString.call(1) // #7
< "[object Number]"
从样本中您可以看到,#2和#3几乎相同,只是它们的左侧和右侧互换了.#2工作正常,但#3给出语法错误.为了使#3正常工作,需要使用一对括号.另外,从#5-7可以看到,只要 {}
不在最左边,它就可以正常工作.
As you can see from the sample, #2 and #3 are almost identical except that the they have the left and right side exchanged. #2 works fine but #3 gives a syntax error. To get #3 to work, a pair of parentheses is required. Additionally, from #5-7 we can see that as long as {}
is not at the left most, it works fine.
但是为什么呢?
推荐答案
在#1中,当找到 rvalue
和运算符 ===
时,javascript认为 lvalue
可以是值或表达式.
In #1, when it finds rvalue
and an operator ===
, javascript considers that the lvalue
could be a value or an expression.
在#2中,与#1相同.因此 {}
被视为对象文字
In #2, same as #1. hence {}
is considered as an object literal
在#3中,由于javascript从右到左评估该语句,因此 {}
只是花括号,而不是对象文字.因此#3不起作用,因为您不会在花括号上使用 toString
函数.
In #3, since javascript evaluates the statement from right to left, the {}
is considered just as a curly brace but not an object literal. hence #3 is not working because you won't be getting toString
function on curly braces.
在#4中,当将 {}
括在()
分组运算符内时,javascript认为它是一个表达式.因此#4之所以有效,是因为 {}
被评估为对象文字,并且 toString
可用.
In #4, when you enclose {}
within ()
grouping operator, javascript thinks it is an expression. hence #4 works because {}
is evaluated as an object literal and toString
be available.
在#5中,与#3相同.javascript认为 {}
只不过是括号,因为没有表达式或表达式.
In #5, same as #3. javascript thinks that {}
as just a brace since there is not expressions or with it.
在#6中,与#4相同.有一个表达式!
.因此被评估为对象
In #6, same as #4. there is an expression !
. hence is evaluated as an object
在#7中,与#4相同.有一个赋值运算符,因此将其作为表达式求值.
In #7, same as #4. there is an assignment operator, hence is evaluated as an expression.
这篇关于直接访问空对象{}上的属性时的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!