Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.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中,var=this_Javascript_This - Fatal编程技术网

在javascript中,var=this

在javascript中,var=this,javascript,this,Javascript,This,有时,我会遇到如下javascript代码: function someFunc() { var that = this; // do something with that } 当你可以直接使用“this”时,人们为什么要这样做?检查这个例子: function someFunc() { var that = this; $('.test').on('click', function() { //in this scope the this will be d

有时,我会遇到如下javascript代码:

function someFunc() {
    var that = this;
    // do something with that
}
当你可以直接使用“this”时,人们为什么要这样做?

检查这个例子:

function someFunc() {
  var that = this;
  $('.test').on('click', function() {
    //in this scope the this will be different and if you'd like to use the this of someFunc then you need to assign another variable
  })
}

因为
这个
并不总是你想要的,因为
这个
以后会被重新定义。通过将原始引用存储在变量中,您仍然可以访问原始作用域的“this”,即使在其他内部作用域中也是如此。这可能会有所帮助:这个问题的答案可能类似于Abbott and Costello例程。@dan1111不,
那个问题,而不是这个问题。