为什么 () => this return 不是封闭对象?
Why doesn't () => this return the enclosing object?
仅供参考,并不重要:我正在使用此代码复制 Node 中的某些行为。js/Express 用于测试 Mocha 的控制器操作。我 return 从 status
方法中 this
的值用于方法链接(res.status(200).json()
在控制器操作中使用),所以 json
方法可以在 res
上调用,因为它是响应对象上的 Express 方法。
从我的 Mocha 测试 运行 看来,this
(res
对象)的值在第一个代码段中正确 returned,我在其中使用 ES6 简洁方法语法 return this
,但不是第二个代码片段,我在其中尝试使用箭头函数来隐式 return this
。我认为使用箭头函数会产生相同的结果,因为在箭头函数中,this
的值是封闭的词法范围(在这种情况下似乎是 res
对象)。
按预期工作; res
似乎被 return 编辑为 status
方法调用的值
const res = {
status() {
return this;
},
json: () => {},
};
没有按预期工作(res
似乎没有 returned 作为 status
方法调用的 this
的值):
const res = {
status: () => this,
json: () => {},
};
为什么 () => this
return 没有封闭对象?
再见根据MDN docs:
In arrow functions, this
retains the value of the enclosing lexical context's this
. In global code, it will be set to the global object:
var globalObject = this;
var foo = (() => this);
console.log(foo() === globalObject); // true
所以在箭头函数中写() => this
和this
基本上是一回事
仅供参考,并不重要:我正在使用此代码复制 Node 中的某些行为。js/Express 用于测试 Mocha 的控制器操作。我 return 从 status
方法中 this
的值用于方法链接(res.status(200).json()
在控制器操作中使用),所以 json
方法可以在 res
上调用,因为它是响应对象上的 Express 方法。
从我的 Mocha 测试 运行 看来,this
(res
对象)的值在第一个代码段中正确 returned,我在其中使用 ES6 简洁方法语法 return this
,但不是第二个代码片段,我在其中尝试使用箭头函数来隐式 return this
。我认为使用箭头函数会产生相同的结果,因为在箭头函数中,this
的值是封闭的词法范围(在这种情况下似乎是 res
对象)。
按预期工作; res
似乎被 return 编辑为 status
方法调用的值
const res = {
status() {
return this;
},
json: () => {},
};
没有按预期工作(res
似乎没有 returned 作为 status
方法调用的 this
的值):
const res = {
status: () => this,
json: () => {},
};
为什么 () => this
return 没有封闭对象?
再见根据MDN docs:
In arrow functions,
this
retains the value of the enclosing lexical context'sthis
. In global code, it will be set to the global object:
var globalObject = this;
var foo = (() => this);
console.log(foo() === globalObject); // true
所以在箭头函数中写() => this
和this
基本上是一回事