开发者

var Object = new Object();

>> typeof Object
"function"   

>> var Object = new Object();

>> typeof Object
"object"

>> var a = new Object()
TypeError: Object is not a constructor

Why it is possible to use "Object" as开发者_运维技巧 a valid variable name?


new Object() will return an object as does {}. So yes, typeof new Object() === "object". The constructor is (as any constructor) a function, so typeof Object === "function".

If you replace the constructor with an object, however, then typeof Object === "object" since Object has become an object like {}. It's the same logic as typeof {} === "object".

Object is not a keyword at all.


These are the reserved words in JavaScript:

break
case
catch
continue
debugger
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with


"Why "Object" is not a specific keyword?"

Because it's not defined as such in the specification.

ECMAScript 7.6.1 Reserved Words


That your code is valid is controlled by two factors:

  • Object is not a "reserved word".

  • Names re-declared in a scope "hide" entities of the same name that were declared in an outer scope. That means that your local variable Object may hide the function Object that exists elsewhere.


What you have done here is using Object class Constructor you have declared Object as new variable. And when you use Object() it will refer to object declared before named Object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜