ES6箭头/功能等效 [英] ES6 arrow / function equivalency
本文介绍了ES6箭头/功能等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
回复
界面。 ES5:
server.decorate('reply','test',function(schema,response){
return this.response(mask(schema,回应));
});
ES6:
code> server.decorate('reply','test',(schema,response)=> {
return this.response(mask(schema,response));
});
E66不起作用,并发出错误:
未收到错误:this.response不是函数
为什么是这样?
解决方案
在这种特殊情况下,库正在更改 / code>指向
decorate
的回调内。当使用箭头函数( =>
)时,此
相当于 code>的外部范围。这意味着您基本上使用
函数
。
I'm just getting around to changing some of my code to ES6 and I ran across some code where the arrow function did not work and I am not sure I understand why. The code is from a plugin for Hapi to decorate the reply
interface.
ES5:
server.decorate('reply', 'test', function(schema, response) {
return this.response(mask(schema, response));
});
ES6:
server.decorate('reply', 'test', (schema, response) => {
return this.response(mask(schema, response));
});
The E66 doesn't work and throws an error:
Uncaught error: this.response is not a function
Why is this?
解决方案
In this particular case, the library is changing what this
refers to inside the callback for decorate
. When using arrow functions (=>
), this
is equivalent to the this
of the outer scope. This means that you're basically stuck using function
for this.
这篇关于ES6箭头/功能等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文