首页 > 解决方案 > JS箭头函数作为对象方法的语法

问题描述

第一次在这里提问。

我通过@CertainPerformance 发现了这个有用的函数,用于按 ID 递归查找嵌套项。

const findItemNested = (arr, itemId, nestingKey) => (
  arr.reduce((a, item) => { 
    if (a) return a;
    if (item.id === itemId) return item;
    if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
  }, null)
);

我无法弄清楚使此函数成为“util”对象上的方法的语法。以下语法不起作用:

var util = {
const findItemNested = (arr, itemId, nestingKey) => (
  arr.reduce((a, item) => { 
    if (a) return a;
    if (item.id === itemId) return item;
    if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
  }, null)
);
}

据我所知,语法需要是这样的:

var util = {
findItemNested: function (arr, itemId, nestingKey) => (
  arr.reduce((a, item) => { 
    if (a) return a;
    if (item.id === itemId) return item;
    if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
  }, null)
);
}

但是这种语法当然行不通。我尝试将箭头函数语法转换为普通函数语法,如下所示(请注意,我已经更改了箭头函数所需的括号,以将对象文字返回为花括号,以匹配对象上的方法所需的语法)。

var util = {
findItemNested: function (arr, itemId, nestingKey) => {
  arr.reduce((a, item) => { 
    if (a) return a;
    if (item.id === itemId) return item;
    if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
  }, null)
}
}

但是,虽然没有编译或运行时错误,但此语法会导致函数返回 undefined 而不是找到存在的嵌套项。

我可以让这个函数工作的唯一方法是将它设置为一个全局可用的函数,并在我的 script.js 文件中使用@CertainPerformance 的原始语法。

有没有办法让这个函数进入我的 var util?提前致谢。

标签: javascriptarrow-functionsobject-literal

解决方案


您正在使用 es6 箭头函数和function关键字。如果您希望它在对象内工作,最好的方法是保持您的代码相同,但删除箭头。您的第二行应如下所示:

findItemNested: function (arr, itemId, nestingKey){

推荐阅读