从自调用嵌套函数引用成员变量
我有这段代码,
var f = function() {
this.x = 100;
(
function() {
x = 20;
}
)();
};
var a = new f;
console.log(a.x);
我想知道为什么在全局范围内创建一个新变量 x,并且输出是 100,而不是 20。 如果我写
var x = 100;
嵌套函数更改相同的 x 值。 似乎通过创建 x
这个.x = 100
将 x 置于函数 f 的范围之外。如果是这样的话,它是在哪里定义的?以及如何访问它?
编辑:修复了一个拼写错误:console.log(ax) 而不是 console.log(x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该语句:
不在当前作用域中创建变量,而是在
this
引用的任何对象上设置属性x
。在您的情况下,this
将是刚刚通过new f
实例化的对象,该对象将由f
返回并分配给一个。
当你说:
JavaScript 在当前作用域中查找
x
但没有找到它,因此它会在下一个作用域中查找,依此类推,直到到达全局作用域。如果它在任何可访问范围内都找不到 x ,它会创建一个新的全局变量,如您所见。要从嵌套函数内访问属性
x
,通常的做法是将this
的引用存储在局部变量中,然后嵌套函数可以引用该变量:方法是在内部函数中引用
this.x
,前提是您通过.call()
方法,以便您可以显式设置this
与(外部)f 中的相同
函数:进一步阅读:
this
运算符The statement:
Does not create a variable in the current scope, it sets a property
x
on whatever objectthis
refers to. In your casethis
will be the object just instantiated vianew f
, the same object that will be returned byf
and assigned toa
.When you say:
JavaScript looks for an
x
in the current scope and doesn't find it, so it looks in the next scope up, etc., until it gets to the global scope. If it doesn't findx
in any accessible scope it creates a new global variable as you have seen.To access the property
x
from within a nested function the usual practice is to store a reference tothis
in a local variable and then the nested function can reference that variable:The other way to do it is to reference
this.x
in the inner function, provided you call the inner function via the.call()
method so that you can explictly setthis
to be the same as in the (outer)f
function:Further reading:
this
operator在 JavaScript 中,变量具有函数级作用域。另外,这:
与:不同,
因为在后面的情况下,
x
具有全局范围(您之前没有使用过var
)范围,例如它成为window<的一部分/代码> 对象。
另外,当您执行以下操作时:
您正在访问通过
x = 20;
设置的全局变量x
,而您应该执行以下操作:In javascript, variables have function-level scope. Also, this:
is differnt from:
because in later case,
x
has global (you have not usedvar
before it) scope eg it becomes part ofwindow
object.Also when you are doing:
You are accessing global variable
x
set viax = 20;
whereas you are suppossed to do:如果您想将匿名函数的乘积分配给
f
的范围,那么以下代码将起作用:if you want to assign the product of the anonymous function to the scope of
f
then the following will work:如果要更改嵌套匿名子函数中的成员函数,您可能需要在作用域内创建指向“this”的指针,如下所示:
If you want to change a member function in a nested, anonymous subfunction, you might want to create a pointer to 'this' within scope, as follows:
当您声明不带
var
的变量时,该变量位于全局范围内。When you declare a variable without
var
, the variable is in global scope.