[英]Javascript: why “this” inside the private function refers to the global scope?
[英]Why `this` refers to the parent function's scope
我确实读过this
关键字可以引用全局范围,也可以引用它所引用的对象或引用事件的对象,但不理解以下行为。
function outer() { var inner = 4; function innerFunc() { var inner = 5; console.log('inner called with ' + this.inner); } return innerFunc; } var obj = outer(); obj();
为什么这个日志4而不是5.AFAIK this
应该引用它所引用的函数,并且应该通过closure
来获得。
TL; DR - this
不会像您认为的那样有效。
函数的this
(也称为上下文)是在调用时确定的,而不是在函数定义时确定的。 众所周知, this
是动态绑定的 ,而闭包的变量是词法绑定的 。
var obj = outer();
obj();
使用this = window
调用outer
(或者在Node.js的情况下调用global
),因为您没有处于严格模式(否则, this = undefined
)。 outer
不使用this
,所以这不会对它产生太大影响。
outer
然后返回一个函数( innerFunc
),并将它分配给obj
。 然后,再次使用this = window
调用obj
(因为您没有使用.bind()
.call()
或.apply()
或.apply()
指定其他内容)。
然后记录this.inner
,它等同于window.inner
,它是undefined
除非你碰巧有一个名为inner
的全局变量带有一些值。
的值this
,然后,由呼叫者决定。
如果你像这样调用了obj
:
obj.call({inner: 42}); // first argument to fn.call() is the context
无论函数是如何定义的,您都会在控制台中看到42。
您的代码片段返回undefined
,而不是4.原因是因为window
通过调用obj()
调用innerFunc
。 因此, this
是指window
因为它被称为innerFunc
(并且window.inner
undefined
)。 您可以通过在代码顶部添加变量inner = 3
来看到这一点(这将使window.inner = 3
),因此您的函数将记录3
。
inner = 3; // ie: window.inner = 3 function outer() { var inner = 4; function innerFunc() { var inner = 5; console.log('inner called with ' + this.inner); // this is window } return innerFunc; } var obj = outer(); obj();
在此示例中,您使用的是函数而不是对象 。 此外,您使用变量而不是this
关键字来分配值。 我认为你所考虑的概念是local scoping
例如,
function parent(){
var n = 5
function child(){
var n = 4 //n is 4 here
}
//n is 5 here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.