javascript - `this` 和 Javascript 回调中的范围

标签 javascript jquery scope this

我直接展示代码:

disable: function(e){
    that = this;
    var haha = this;
    $.post(url, function(){
        console.log(this);// (why ajax object here?
        console.log(that);// (I understand this one works
        console.log(haha);// ReferenceError 
    })
}

我在这里感到困惑的是:

  1. 为什么回调中的this不引用外部的?我认为回调中的 this 遵循默认的绑定(bind) Angular 色。
  2. 为什么haha不指代that呢?我认为当在本地范围内找不到 haha 时,它将转到外部范围。

我知道使用that不是一个好方法。这就是为什么我尝试哈哈,但失败了。 enter image description here

最佳答案

我认为您正在尝试从控制台访问这些值...在这种情况下,哈哈将不起作用,因为它是函数的本地函数,正如您创建的那样 作为全局变量(因为没有使用 var)。

但这是一个错误的模式,因为其他一些脚本可能会在 ajax 请求完成之前修改 that 的值。

关于javascript - `this` 和 Javascript 回调中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337858/

相关文章:

javascript - 模糊时触发的输入更改事件

jquery - 使页脚小部件重新调整到相同的高度

iphone - 变量超出范围

java - Java构造函数中的StringBuffer?

javascript - 如何在 Cloud Functions for Firebase 上使用 Express 执行 HTTP 文件上传(multer、busboy)

javascript - 单击后重新启用按钮@click.once

javascript - 如何让AmChart跟随视频元素同步

javascript - toggleClass 不会改变类

javascript - 如何在下面提供的 JS fiddle 圆形进度条上获得箭头形状

javascript - Animate CC HTML5 尝试通过调用字符串来更改全局变量