Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly reference "this"? [duplicate]

Assuming I have the following:

var object = {
    myfunc: function() {
        $.ajax({
           url: url,
           format: format,
           success: function() {

           console.log(this) // This refers to the ajax call and not "object"

                $.ajax({
                  url: url,
                  format: format,
                  success: function() {
                    console.log(this) // this refers to nested ajax call and not "object"
                  }
                });


           }
        });
    }
}

How to get "this" to reference "object" as opposed to the ajax call?

like image 633
Rolando Avatar asked Sep 15 '26 17:09

Rolando


2 Answers

Use $.proxy() to pass a custom context to a callback function

var object = {
    myvar : "hello",
    myfunc : function() {
        $.ajax({
            url : url,
            format : format,
            success : $.proxy(function() {

                console.log(this) // This refers to the ajax
                // call and
                // not "object"

                $.ajax({
                    url : url,
                    format : format,
                    success : function() {
                        console.log(this) // this
                        // refers to
                        // nested ajax call
                        // and not "object"
                    }
                });

            }, this)
        });
    }
}
like image 135
Arun P Johny Avatar answered Sep 17 '26 05:09

Arun P Johny


Copy the value of this to another variable when you are still in the context where this holds the value you want.

var object = {
    myfunc: function() {
        var myObject = this;
        $.ajax({

Then use that variable (which will be in scope for functions declared inside it, unless they mask it with another variable of the same name) instead.

success: function() {
    console.log(myObject);
}
like image 27
Quentin Avatar answered Sep 17 '26 07:09

Quentin



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!