我想知道是否可以从下面的代码中的window.updateFoo()访问foo:
function f1 () {
'use strict';
this.x = {};
this.x.foo = 0;
window.updateFoo = function(val){
this.x.foo = val; // Obviously wrong since 'this' doesn't refer to f1 now. Uncaught TypeError: Cannot set property 'foo' of undefined
};
window.updateFoo(20); // Try changing the value of this.x.foo?
}
答案 0 :(得分:2)
当您致电window.updateFoo
时,会在window
的上下文中调用它。您最好的选择是将this
保存在变量中,然后在函数中使用它:
function f1 () {
'use strict';
this.x = {}; // Object for 'const' variables
this.x.foo = 0;
var _this = this;
window.updateFoo = function(val){
_this.x.foo = val; // Use saved version
};
window.updateFoo(20); // Try changing the value of this.x.foo?
}
另一个选项,但它只能在f1
内使用,是在特定情况下调用updateFoo
:
window.updateFoo.call(this, 20);
答案 1 :(得分:1)
是的,你正在创建一个闭包。在闭包中,内部函数可以访问外部函数变量。但是,您应该创建另一个变量以引用function f1
,因为this
的上下文将是错误的。直接调用函数时,this
引用全局对象或窗口。
function f1(){
'use strict';
this.x = {}; // Object for 'const' variables
this.x.foo = 0;
var that = this;
window.updateFoo = function(val){
that.x.foo = val; // Obviously wrong since 'this' doesn't refer to f1 now. Uncaught TypeError: Cannot set property 'foo' of undefined
};
window.updateFoo(20);
}
答案 2 :(得分:1)
您还可以将“this”的上下文绑定到您想要的方法。
window.updateFoo = function(val){
this.x.foo = val;
}.bind(this)
答案 3 :(得分:1)
您可以使用bind()
嗯,.bind()只是创建一个新函数,在调用时,将其关键字设置为提供的值。
More on understanding bind
here.
this.x = {};
this.x.foo = 0;
var func = function(val) {
this.x.foo = val;
}.bind(this);
像这样:
function f1() {
'use strict';
this.x = {};
this.x.foo = 0;
window.updateFoo = function(val) {
this.x.foo = val;
}.bind(this);
window.updateFoo(10);
alert(this.x.foo); // alerts '10'
}
f1();
这里有一点解释: