在 JS 中具有正确的“this"值 [英] Having the correct value of 'this' in JS
问题描述
我有两个类似的 Javascript对象"......
I have two Javascript "objects" similar to so....
var Object2 = new (function() {
this.FetchData = function(callback) {
// do some stuff
callback(data);
};
});
var Object1 = new (function() {
this.DisplayStuff = function() {
};
this.LoadData = function() {
Object2.FetchData(this.OnData);
};
this.OnData = function(data) {
// this == window
this.DisplayStuff(); // doesn't work
};
});
当 Object1 接收到 OnData 的回调时,this"的值被设置为 window.有什么办法可以解决这个问题,使 OnData 中this"的值成为 Object1 的实例而不是窗口?
When Object1 receives the callback to OnData, the value of "this" is set to window. Is there any way I can get around this so that the value of "this" inside of OnData will be the instance of Object1 instead of window?
推荐答案
这样做的简单方法是在变量中存储对 this 的引用,然后使用 call() 方法:
The simple way of doing it is storing a reference to this in a variable, then using the call() method:
this.LoadData = function() {
var self = this;
Object2.FetchData(function () { self.OnData.call(self) });
};
如果您经常这样做,您可能需要考虑在 ECMAScript 第 5 版中的函数原型上使用 .bind() 方法.可以在不受支持的情况下实现此方法:
If you're doing this a lot, you might want to consider using the .bind() method on the function prototype in ECMAScript 5th edition. This method can be implemented where unsupported:
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
以及由此产生的函数调用:
And the resulting function call:
this.LoadData = function() {
Object2.FetchData(this.OnData.bind(this));
};
这篇关于在 JS 中具有正确的“this"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!