【发布时间】:2016-09-25 15:33:40
【问题描述】:
当我运行下面的 IFFE 时,为什么 this 关键字引用 window 对象而不是 a 变量?
var a = {
printThis : function () {
console.log('printThis', this);
var inner = (function () {
console.log('inner', this);
})();
}
};
a.printThis();
产生以下输出:
printThis **an object**
inner **window object** <-- why..?
var a = {
printThis: function() {
console.log('printThis', this);
var inner = (function() {
console.log('inner', this);
})();
}
};
a.printThis();
【问题讨论】:
-
你没有打电话给
a.inner(),只是inner()。所以a不会变成this。 -
但它也在一个 then 里面..
-
没关系。每个函数都有自己的
this。如果要保留外部this,则必须使用bind或var self = this或“胖箭头”。 -
你能解释一下这对 JavaScript 引擎是如何工作的吗?
标签: javascript javascript-objects