简体   繁体   English

Javascript 标识符已声明

[英]Javascript identifier already declared

Why does the outer declaration cause an identifier error, while the inner declaration is fine?为什么外层声明会导致标识符错误,而内层声明没有问题?

 function outer() { function inner() { console.log('Executing inner function'); } var inner = new inner(); } var outer = new outer();

If you change the last line to var x = new outer();如果将最后一行更改为var x = new outer(); , it'll run fine. ,它会运行良好。

I believe you have found the answer yourself.我相信你自己已经找到了答案。 In this case, there is a confusion in the language flow due to the use of the same name for the function ( function outer() ), global variable ( var outer ) and object ( new inner() ).在这种情况下,由于函数 ( function outer() )、全局变量 ( var outer ) 和对象 ( new inner() ) 使用相同的名称,语言流会出现混乱。 Be more semantic with the name of the functions, variables and objects you intend to use.使用您打算使用的函数、变量和对象的名称更具语义。

This is because of Local and Global declarations of Variables/Objects.这是因为变量/对象的局部和全局声明。

1. var inner is considered as a local variable and it can have the same name . 1. var inner 被认为是一个局部变量,它可以具有相同的名称。

2. var outer is declared outside of Outer Function. 2. var outer 是在外部函数之外声明的。 So it is considered as an non local variable.所以它被认为是一个非局部变量。 So it must have an unique name than the existing ones.因此,它必须具有比现有名称唯一的名称。

I restructured your code in a way that works with your original idea.我以适合您最初想法的方式重组了您的代码。 Basically I read the MDN documentation about possible errors with the new operator.基本上,我阅读了有关新操作员可能出现的错误的 MDN 文档。 What happens is that the new operator needs a function that defines a scope so that only afterwards can it be stored in a variable and can return whatever you want.发生的情况是 new 运算符需要一个定义作用域的函数,以便之后它才能存储在变量中并可以返回任何你想要的。 In the documentation of this part there are some examples of errors that I believe would clarify your doubts.在这部分的文档中,有一些错误示例,我相信可以澄清您的疑虑。 MDN: TypeError: "x" is not a constructor MDN:类型错误:“x”不是构造函数

 function showTheOuterFn() { function fnInner() { console.log('Executing inner function'); } let getInner = new fnInner(); } let outer = new showTheOuterFn();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM