我直接展示代码:
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
})
}
我在这里感到困惑的是:
- 为什么回调中的
this
不引用外部的?我认为回调中的this
遵循默认的绑定(bind) Angular 色。 - 为什么
haha
不指代that
呢?我认为当在本地范围内找不到haha
时,它将转到外部范围。
最佳答案
我认为您正在尝试从控制台访问这些值...在这种情况下,哈哈
将不起作用,因为它是函数的本地函数,正如您创建的那样
作为全局变量(因为没有使用 var
)。
但这是一个错误的模式,因为其他一些脚本可能会在 ajax 请求完成之前修改 that
的值。
关于javascript - `this` 和 Javascript 回调中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337858/