以下是三种方法,最现代的方法是首先:
loadGroups(){
axios.get('/api/groups')
.then(response => { // for arrow functions `this` is just another variable
// handle success
this.groups = response.data;
});
}
loadGroups(){
axios.get('/api/groups')
.then(function (response) {
// handle success
this.groups = response.data;
}.bind(this)); // binding `this` to the function makes it keep `this`
}
loadGroups(){
var that = this; // old style approach with a proxy variable
axios.get('/api/groups')
.then(function (response) {
// handle success
that.groups = response.data;
});
}
你的原因
this
正在丢失的是回调不是作为方法调用的。当函数定义为
function
关键字(不是箭头),然后从对象的属性调用它(即在某个地方有一个点-或至少是方括号)。对象被称为“receiver”,并被分配给
这
.
const obj = {
not_method: x => x * 2,
method: function(x) { return x*2; }
}
obj.not_method() // not a method call (arrow); `this` is unaffected
f = obj.method; f() // not a method call (not property); `this` is `global` or `window`
obj.method() // method call; `this` is `obj`
obj['method']() // still a method call; `this` is obj
axios.get
不在乎
这
;它接收一个参数,例如
callback
,并称之为:
callback(response)
;因为在
回拨
,这不是方法调用,而且
这
是全球范围。
第一段代码将函数更改为箭头函数。箭头函数的定义是完全忽略
这
,将其视为任何其他变量。因此,
这
将被函数关闭,您可以从闭包中访问它,以获取它在闭包之外的值。
第二段代码使用
Function.prototype.bind
强制指定函数
这
以我们选择的价值。它也可以填充一些参数,但我们并不是用它来填充的,只是接收器。
第三段代码模拟了第一段代码,在箭头函数成为一件事之前。我们将
这
到另一个变量,这不是魔术般的
这
,因此将被正常机制捕获到闭包中。