[英]Variable scope inside constructor
In JavaScript, functions can always access global variables. 在JavaScript中,函数始终可以访问全局变量。 I have a class that I am using, and it references global variables.
我有一个正在使用的类,它引用了全局变量。 Here's a similar class:
这是一个类似的类:
function Test(){
this.abc = abc;
}
If I set the global abc
then call this, it works. 如果我设置了全局
abc
然后调用它,它将起作用。
var abc = 123,
testA = new Test;
console.log(testA.abc); // 123
But what if I don't want abc
to be global? 但是,如果我不希望
abc
成为全球性的怎么办? I wrapped the code in a function call, but I get an error saying abc is not defined
. 我将代码包装在一个函数调用中,但是收到一条错误消息说
abc is not defined
。
(function(){
var abc = 123,
testA = new Test; // ERROR: abc is not defined
console.log(testA.abc);
})();
How can I read local variables inside a JavaScript constructor without adding variables to the global scope? 如何在不向全局范围添加变量的情况下在JavaScript构造函数中读取局部变量?
The problem is that local variables have lexical scope. 问题在于局部变量具有词法范围。
That means that to be resolved they must be within the same code block, or in enclosing code blocks. 这意味着要解决这些问题,它们必须在同一代码块中,或在封闭的代码块中。
Your code would only work if the definition of Test
was also within the IIFE: 仅当
Test
的定义也在IIFE中时,您的代码才有效:
(function(){
var abc = 123,
testA = new Test; // ERROR: abc is undefined
function Test() { // this will be hoisted
this.abc = abc;
}
console.log(testA.abc);
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.