Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function scope

I'm trying to call an instance method a() from within a jQuery ajax call. But when I do so, it says that the method is not defined. I think it's because a() is not within the scope of $. But I thought it would be part of the scope chain. How can a() be within scope?

function Z() {
    this.x = 0
    this.a = function() {
      return this.x;   
    }
    this.b = function() {
        $.ajax({
            ...
            success: function(data, textStatus, xhr) {
                this.a(); //a() is not defined
            },
            ...
        }); 
    }  
}

z = new Z();
z.b();
like image 909
CoolGravatar Avatar asked Feb 19 '26 21:02

CoolGravatar


1 Answers

Most people will suggest a trick like var that = this;, but I prefer using function binding to achieve the same end more elegantly and clearly.

Create a local function a, which is this.a bound to this:

function Z() {
    this.x = 0
    this.a = function() {
      return this.x;   
    }
    this.b = function() {
        var a = this.a.bind(this);
        $.ajax({
            ...
            success: function(data, textStatus, xhr) {
                a();
            },
            ...
        }); 
    }  
}

z = new Z();
z.b();
like image 54
Delan Azabani Avatar answered Feb 21 '26 11:02

Delan Azabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!