ES6箭头/功能等效

cyb*_*bat 4 javascript ecmascript-6

我只是将我的一些代码更改为ES6,并且我遇到了一些代码,其中箭头功能不起作用,我不确定我理解为什么.代码来自Hapi的插件来装饰reply界面.

ES5:

server.decorate('reply', 'test', function(schema, response) {
  return this.response(mask(schema, response));
});
Run Code Online (Sandbox Code Playgroud)

ES6:

server.decorate('reply', 'test', (schema, response) => {
  return this.response(mask(schema, response));
});
Run Code Online (Sandbox Code Playgroud)

E66不起作用并抛出错误:

Uncaught error: this.response is not a function
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

Sei*_*ria 6

在这种特殊情况下,库正在改变this回调内部的内容decorate.使用箭头函数(=>)时,this相当于this外部范围.这意味着你基本上不能使用function它.