我有以下代码(简化)
var Page = new UI('page.html');
Page.onLoad = function(html){
this.name = 'Page 1';
Util.test(this.run);
};
Page.run = function(){
console.log(this.name); // undefined
console.log(Page.name); // correct
};
var Util = function(){};
Util.prototype.test = function(callback){
// when finished run the callback
callback();
};
我的问题是为什么我不能使用this
关键字如果执行离开对象然后返回?请解释我应该更改什么才能访问 this
再次。
最佳答案
您可以将“this”绑定(bind)到函数 run,如下所示。
Page.onLoad = function(html){
this.name = 'Page 1';
Util.test(this.run.bind(this));
};
您可以找到有关函数“bind”的更多信息。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
关于javascript - JavaScript 中的 this 关键字和函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42019532/