最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - var Object = new Object(); - Stack Overflow

programmeradmin4浏览0评论
>> 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?

>> 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?

Share edited Sep 20, 2011 at 11:52 JohnJohnGa asked Sep 20, 2011 at 11:44 JohnJohnGaJohnJohnGa 15.7k20 gold badges64 silver badges87 bronze badges 6
  • Object is already an object, perhaps? (And not a constructor for new objects furthermore) – rabudde Commented Sep 20, 2011 at 11:46
  • 1 @rabudde: I believe his question is "why can I do this? - why do I not get something like SyntaxError: assignment to keyword?" (as you get in Python 3 for a line like True = False - which you could do in Python 2) – Chris Morgan Commented Sep 20, 2011 at 11:48
  • Why do you want to close this question? care to ment? – JohnJohnGa Commented Sep 20, 2011 at 11:49
  • 3 @JohnJohnGa: you could make the question a lot clearer. – Chris Morgan Commented Sep 20, 2011 at 11:50
  • var a = {}; typeof(a) === 'object'; – ant_Ti Commented Sep 20, 2011 at 11:50
 |  Show 1 more ment

5 Answers 5

Reset to default 3

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 bee 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)

  1. 暂无评论