I was wondering if it is possible to access foo from window.updateFoo() in the code below:
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?
}
When you call window.updateFoo
, it is called in the context of window
. Your best option is to save this
in a variable, and then use that in the function:
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?
}
The other option, but it will only work within f1
, is to call updateFoo
will a specific context:
window.updateFoo.call(this, 20);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다