Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我可以扩大';这';在下面的例子中?_Javascript_Jquery - Fatal编程技术网

Javascript 我可以扩大';这';在下面的例子中?

Javascript 我可以扩大';这';在下面的例子中?,javascript,jquery,Javascript,Jquery,在使用jquery回调时,我发现不再定义“this”。我找到了一个解决办法,就是将“this”设置为另一个变量。例如,像这样: function handler(DATA) { var myThis = this; $.post( 'file.php', DATA, function() { // THIS where I need access to 'this', but

在使用jquery回调时,我发现不再定义“this”。我找到了一个解决办法,就是将“this”设置为另一个变量。例如,像这样:

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

          }
       );
}
它是这样工作的,但我总是在寻找“正确的方式”或“更好的方式”来做事


这是最好的方式吗?或者还有别的吗?

这很好。在我的项目中,我总是这样做,尤其是在Ajax调用中

但是,请确保将
var
放在
myThis
之前,否则它将在全局范围内声明,这是您绝对不希望看到的

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

          }
       );
}
我喜欢使用“自我”:

您也可以使用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(){}
  });
}

您可能希望在
myThis=this前面抛出一个
var
但是你这样做是很常见的做法是的,实际上我的代码中有var,但我没有复制/粘贴,不管是什么原因:)我希望有一种更平滑、更流畅的方法,但并不总是这样。
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(){}
  });
}