【发布时间】:2017-08-31 21:35:47
【问题描述】:
受this article 的启发,我一直在重构一些旧代码。
但是,我在使用Array.prototype.filter 传递参数时遇到了问题,因为Array.prototype.filter(callback, thisArg) 的第二个参数在回调中绑定了this-object,但箭头函数不绑定this。
在我的示例中,我使用 Object.keys() 从关联数组中获取键(是的,我知道,技术上在 JavaScript 中不可用),然后通过关联数组 @987654328 中对象的属性过滤该数组@,但由于此绑定不可用,因此失败。
那么,拥抱箭头函数,如何将参数传递给filter()中的回调?
const arr = {
a: {
property: true,
otherProp: false
},
b: {
property: true,
otherProp: false
},
},
hasProperty = item => this[item].property,
getMatchingKeys = object => Object.keys(object).filter(hasProperty, object);
getMatchingKeys(arr);
【问题讨论】:
-
为什么首先需要涉及
this?.filter(v => arr[v].property)非常易读且简短。 -
hasProperty和getMatchingKeys真的应该在arr对象字面量内吗? -
如果您需要
this作为方法上下文,请不要使用箭头函数。 -
"所以,拥抱箭头函数" - 这显然是错误的态度。一个人应该只在有用的地方使用箭头,而不应该尝试在它们不起作用的地方使用它们。
标签: javascript arrays ecmascript-6 arrow-functions