Invoke a javascript object method from within a callback

前端 未结 3 459
北恋
北恋 2020-12-15 05:55

I define the following MyClass and its methods in a user script:

function MyClass() {
    this.myCallback = function() {
        alert(\"MyClass         


        
相关标签:
3条回答
  • 2020-12-15 06:27

    Store a reference to the instance and use it:

    function MyClass() {
        this.myCallback = function() {
            alert("MyClass.myCallback()");
        };
    
        var instance = this;
    
        instance.startRequest = function() {
            GM_xmlhttpRequest({
                'method': 'GET',
                'url': "http://www.google.com/",
                'onload': function (xhr) {
                    instance.myCallback();
                }
            });
        };
    }
    
    0 讨论(0)
  • 2020-12-15 06:30

    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();
             }
         });
     };
    
    0 讨论(0)
  • 2020-12-15 06:45

    The simplest solution, as already was pointed out, is creating an alias for the this that stays in scope. The most popular variable names for the alias are things like self or that, but anything works, really.

    The other alternative (that might or might not be better, depending on the use case) is binding the method into a "plain" function and using that instead:

    var f = this.callback.bind(this);
    
    ...
    'onload': function(){
        f();
    }
    

    bind is not supported on old browsers, but you can find alternatives in many JS frameworks. The example I gave doesn't look that good, but it can be very convenient when you want to pass your method directly as a callback function (you might also get partial function application as well and that is very neat)

    0 讨论(0)
提交回复
热议问题