从回调中调用javascript对象方法 [英] Invoke a javascript object method from within a callback
问题描述
我在用户脚本中定义了以下 MyClass
及其方法:
I define the following MyClass
and its methods in a user script:
function MyClass() {
this.myCallback = function() {
alert("MyClass.myCallback()");
};
this.startRequest = function() {
GM_xmlhttpRequest({
'method': 'GET',
'url': "http://www.google.com/",
'onload': function (xhr) {
myClassInstance.myCallback();
}
});
};
}
var myClassInstance = new MyClass();
myClassInstance.startRequest();
这个脚本工作, myCallback()
方法将在 GM_xmlhttpRequest 完成后调用。
This script works and the myCallback()
method gets called once the GM_xmlhttpRequest completes.
但是,它只能工作,因为 onload
callback是指全局变量 myClassInstance
。如果我将 onload
回调更新为:
However, it only works because the onload
callback is referring to the global variable myClassInstance
. If I update the onload
callback to:
'onload': function (xhr) {
this.myCallback();
}
然后我得到了(Chrome)错误:
Then I get the (Chrome) error:
未捕获TypeError:Object [object DOMWindow]没有方法'myCallback'。
Uncaught TypeError: Object [object DOMWindow] has no method 'myCallback'.
似乎这个
正在错误的上下文中被评估。
It seems this
is being evaluated in the wrong context.
有没有办法调用
无需使用全局变量?
Is there a way to invoke the myCallback()
method of myClassInstance
without having to resort to using a global variable?
推荐答案
将保存到变量中时, c>然后你可以稍后再参考:
Save the correct this
, when it is in scope, into a variable. Then you can reference it later:
this.startRequest = function() {
var myself = this;
GM_xmlhttpRequest({
'method': 'GET',
'url': "http://www.google.com/",
'onload': function (xhr) {
myself.myCallback();
}
});
};
这篇关于从回调中调用javascript对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!