为什么IIFE这个关键字指的是窗口对象..? [英] Why IIFE this keyword refers to window object..?
问题描述
当我运行以下代码时,为什么IFFE 此引用窗口对象而不是 a
When I run the below code why the IFFE this refers to window object and not to a
var a = {
printThis : function () {
console.log('printThis', this);
var inner = (function () {
console.log('inner', this);
})();
}
};
a.printThis();
a.printThis();
//输出
printThis 一个对象
printThis a object
内部窗口对象< - 为什么..?
inner window object <-- why..?
推荐答案
请考虑以下示例:
var a = {};
var b = {};
a.hello = function() { console.log(this); };
b.hello = a.hello;
在大多数编程语言中, b.hello()
将打印 a
,因为它们基于这个
来确定函数的位置。该函数在 a
中,所以此
是 a
。有道理,对吗?
In most programming languages, b.hello()
would print a
since they base this
on where the function is. The function is in a
, so this
is a
. Makes sense, right?
然而,JavaScript在这方面有点不同。而不是它在哪里,它基于如何被称为。 b.hello()
在 b
上调用 hello
,从而此
设置为 b
。这也是有道理的,因为JavaScript并没有真正具有where函数的概念(不像Java中的方法,它总是与特定的类绑定),并且很难确定 a
就是是。
However, JavaScript is a bit different in that regard. 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
. 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".
所以, foo.bar()
对于栏$>的调用,将始终将
绑定到特定值)。此
设置为 foo
c $ c>(除非有人使用 bind
或类似的事先将此
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).
现在,一个IIFE被调用......没什么,真的。它不是 foo.bar()
的情况,它只是一个 bar()
其中 bar
是你的函数表达式。在这种情况下,没有 foo
,它默认为窗口
对象。
Now, an IIFE is invoked on... nothing, really. It's not a foo.bar()
situation, it's just a bar()
where bar
is your function expression. In cases like this where there's no foo
, it defaults to the window
object.
有两种简单的解决方法:
There are two simple workarounds:
- 在IIFE之外创建一个包含您感兴趣的值的变量:
var that = this;
并使用此
在IIFE中,或 -
bind
此
值:(function(){CODE GOES HERE})。bind(this)();
- Create a variable outside the IIFE containing the value you´re interested in:
var that = this;
and usethat
instead ofthis
in the IIFE, or bind
thethis
value:(function(){ CODE GOES HERE }).bind(this)();
这篇关于为什么IIFE这个关键字指的是窗口对象..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!