Javascript 胖箭代表团
我正在将一些代码转换为ES6,其中一部分我试图理解fat arrow绑定。我有这样的代码:Javascript 胖箭代表团,javascript,ecmascript-6,Javascript,Ecmascript 6,我正在将一些代码转换为ES6,其中一部分我试图理解fat arrow绑定。我有这样的代码: function callApi(api, payload, header) { $http.post(api, payload, header) .success(function(data) {...}) .error(function (data, status) { handleError(data, status) }) } function handleError(d
function callApi(api, payload, header) {
$http.post(api, payload, header)
.success(function(data) {...})
.error(function (data, status) { handleError(data, status) })
}
function handleError(data, status) {...}
.error((data, status) => this.handleError)
我已将其更改为以下内容:
callApi(api, payload, header) {
this.$http.post(api, payload, header)
.success((data) => {...})
.error((data, status) => this.handleError(data, status))
}
handleError(data, status) {...}
不起作用的是当我试着这样称呼handleError时:
function callApi(api, payload, header) {
$http.post(api, payload, header)
.success(function(data) {...})
.error(function (data, status) { handleError(data, status) })
}
function handleError(data, status) {...}
.error((data, status) => this.handleError)
我认为这可能是将错误处理委托给handleError函数,但事实并非如此。有人能帮我理解我对箭头绑定的误解,它不能像()=>myFunction那样使用,有没有一种方法可以像这样进行委托,它包含绑定
this
?箭头函数的this
值就是包含函数的this
。它不会创建自己的此
我已将其更改为(数据、状态)=>this.handleError(…)
,它可以工作
我担心handleError
和this.handleError
是否都起作用。这可能表明您已将它们放在全局范围内,并且在没有接收器的情况下调用您的函数。我建议调用直接引用(仅handleError(…)
)并使用(这将成为ES6的默认设置)
不起作用的是当我试图像这样调用handleError时:(数据,状态)=>this.handleError
很简单:您没有在这里调用它,而是编写了一个arrow函数,返回handleError
函数
通过完全不使用箭头函数,您应该能够简化代码:
callApi(api, payload, header) {
this.$http.post(api, payload, header)
.success((data) => {...})
.error(handleError)
}
或者,如果handleError
是this
的一种方法,并且依赖于实例的调用,那么您应该使用:
在这种情况下,您原来的ES5不应该工作,但是 (a,b)=>c
与函数(a,b){return c}相同。bind(this)
应该是。error(handleError)
不需要ES6才能正常工作。。error(handleError)
导致“handleError not defined”.error(this.handleError)
r当我尝试使用this
时,导致handleError内部出现错误this
未定义。.error(this.handleError.bind(this))
我可以将注释标记为接受的答案吗?谢谢@埃尔克兰斯也说了类似的话。这对我有效:.error(This.handleError.bind(This))