Can I zoom in on this in the following example?

When using jquery callback, I found that 'this' is no longer defined. I found a job which is to set 'this' to another variable. For example, for example:

function handler(DATA) {
       var myThis = this;

       $.post(
          'file.php',
          DATA,
          function() {

               // THIS where I need access to 'this', but its not available
               // unless I've used the 'myThis' trick above

          }
       );
}

It works like that, but I'm always looking for the “right way” or “best way” to do something.

Is this the best way? or is there another?

+3
source share
2 answers

This is normal. I do this all the time in my projects, especially with Ajax calls.

But do not forget to put varbefore myThis, otherwise it will be declared in the global scope, which you definitely do not need.

function handler(DATA) {
       var myThis = this;

       $.post(
          'file.php',
          DATA,
          function() {

               // THIS where I need access to 'this', but its not available
               // unless I've used the 'myThis' trick above

          }
       );
}
+5

"self": ​​

function handler(DATA) {
   var self = this;
   $.ajax({
      "url":"file.php",
      "type":"post",
      "data":DATA,
      "success":function() {
           // THIS where I need access to 'this', but its not available
           // unless I've used the 'myThis' trick above
      },
      "error":function(){
          alert("ERROR!")
      }
    });
}

- jQuery... , , .

function handler(DATA) {
   var success = $.proxy(function(){
       // use "this" in this function to refer to the scope 
       // you were assigning to "myThis" in your example
   }, this);
   $.ajax({
      "url":"file.php",
      "type":"post",
      "data":DATA,
      "success":success,
      "error":function(){}
  });
}
+1

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


All Articles