JQuery: reference to an outer scope in a callback

I have a problem with OO Javascript and jQuery callback. If you look at the sample below, it should explain everything.

How can I call the functionToCall () function deep inside this functception.

function outerClass() { this.functionToCall = function() { //do something } this.someOtherFunction = function() { this.aCoupleOfVariables1 = 2; this.aCoupleOfVariables2 = "stuff"; $.ajax({ success: function() { //How do I call functionToCall() right here //TRIED: functionToCall(); this.functionToCall(); that.functionToCall(); } }); } } 
+6
source share
5 answers

You can pass this as the context parameter in $. ajax () :

 $.ajax({ context: this, success: function() { // Here, 'this' refers to the same object as in the caller. this.functionToCall(); } }); 
+14
source

Enter a local link,

 function outerClass() { var self = this; this.functionToCall = function() { //do something } this.someOtherFunction = function() { this.aCoupleOfVariables1 = 2; this.aCoupleOfVariables2 = "stuff"; $.ajax({ success: function() { self.functionToCall(); } }); } } 
+6
source

You need to determine that in the outside area.

 function outerClass() { var that = this; // ... $.ajax({ success: function() { that.functionToCall(); } }); } 
+5
source

You need to save the link for this value from the parent scope:

 var parentScope = this; 

and then access to functionToCall through this object

 parentScope.functionToCall(); 

Example:

 function outerClass() { var parentScope = this; this.functionToCall = function() { //do something } // ... $.ajax({ success: function() { parentScope.functionToCall(); } }); } 

Another way to achieve this would be to use Es5 .bind() to set the this value inside your internal function (-context)

 $.ajax({ success: function() { // Here, 'this' refers to the same object as in the caller. this.functionToCall(); }.bind(this) }); 
+4
source

Maintain the scope of the function in a local variable and use it or you can also use jquery proxy in which you can specify the context.

 function outerClass() { this.functionToCall = function() { //do something } this.someOtherFunction = function() { this.aCoupleOfVariables1 = 2; this.aCoupleOfVariables2 = "stuff"; $.ajax({ success: $.proxy(function() { this.functionToCall(); }, this) }); } } 
+2
source

Source: https://habr.com/ru/post/894639/


All Articles