从回调中调用 javascript 对象方法 [英] Invoke a javascript object method from within a callback

查看:25
本文介绍了从回调中调用 javascript 对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用户脚本中定义了以下 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();

此脚本有效,一旦 GM_xmlhttpRequest 完成,就会调用 myCallback() 方法.

This script works and the myCallback() method gets called once the GM_xmlhttpRequest completes.

然而,这只是因为 onload 回调引用了全局变量 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:

未捕获的类型错误:对象 [object DOMWindow] 没有方法myCallback".

Uncaught TypeError: Object [object DOMWindow] has no method 'myCallback'.

this 似乎在错误的上下文中被评估.

It seems this is being evaluated in the wrong context.

有没有办法调用 myClassInstancemyCallback() 方法而不必求助于全局变量?

Is there a way to invoke the myCallback() method of myClassInstance without having to resort to using a global variable?

推荐答案

将正确的this(在范围内)保存到变量中.那你以后可以参考:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆