当我运行下面的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
。 - Thilothis
。如果您想保留外部的this
,则必须使用bind
或var self = this
或“fat arrow”。 - Thilo