[英]Why IIFE this keyword refers to window object..?
When I run the below IFFE, why does the this
keyword refer to the window
object and not to a
variable?当我运行以下IFFE,为什么this
关键字指的是window
对象,而不是a
变量?
var a = {
printThis : function () {
console.log('printThis', this);
var inner = (function () {
console.log('inner', this);
})();
}
};
a.printThis();
Result in the following output:导致以下输出:
printThis **an object**
inner **window object** <-- why..?
var a = { printThis: function() { console.log('printThis', this); var inner = (function() { console.log('inner', this); })(); } }; a.printThis();
Consider the following example:考虑以下示例:
var a = {};
var b = {};
a.hello = function() { console.log(this); };
b.hello = a.hello;
In most programming languages, b.hello()
would print a
since they base this
on where the function is.在大多数编程语言, b.hello()
将打印a
,因为他们立足this
在哪里的功能。 The function is in a
, so this
is a
.函数在a
,所以this
是a
。 Makes sense, right?有道理吧?
However, JavaScript is a bit different in that regard.然而,JavaScript 在这方面有点不同。 Instead of where it is , it's based on how it was called .它不是它在哪里,而是基于它的调用方式。 b.hello()
calls hello
on b
, thus this
is set to b
. b.hello()
在b
上调用hello
,因此this
被设置为b
。 This also makes sense since JavaScript doesn't really have a concept of "where" a function is (unlike methods in, say, Java, which are always tied to a specific class), and it's hard to determine that a
is where it "is".这也是有道理的,因为 JavaScript 并没有真正的函数“在哪里”的概念(不像 Java 中的方法,它总是与特定的类相关联),并且很难确定a
是它的位置“是”。
So, foo.bar()
will always set this
to foo
for the purposes of this call to bar
(unless one has used bind
or similar to bind this
to a specific value in advance).因此, foo.bar()
将始终将this
设置为foo
以用于对bar
调用(除非已经使用bind
或类似方法预先将this
绑定到特定值)。
Now, an IIFE is invoked on... nothing, really.现在,一个 IIFE 被调用...没有,真的。 It's not a foo.bar()
situation, it's just a bar()
where bar
is your function expression.这不是foo.bar()
情况,它只是bar()
,其中bar
是您的函数表达式。 In cases like this where there's no foo
, it defaults to the window
object.在没有foo
,它默认为window
对象。
There are two simple workarounds:有两种简单的解决方法:
var that = this;
在 IIFE 之外创建一个包含您感兴趣的值的变量: var that = this;
and use that
instead of this
in the IIFE, or并且使用that
不是this
在IIFE,或bind
the this
value: (function(){ CODE GOES HERE }).bind(this)();
bind
this
值: (function(){ CODE GOES HERE }).bind(this)();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.