传递anon函数时没有定义Error属性(如何咖喱)?

时间:2016-11-21 23:06:24

标签: javascript functional-programming ecmascript-6 currying

我认为这种技术叫做currying。

问题:

https://repl.it/E4iG

ReferenceError: type is not defined
    at hasType:14:27
    at allApprovalTypes.map:18:26
    at eval:17:21
    at eval

问题: 我如何使用hasType,最后我可以将未命名的匿名函数替换为approvals.find(hasType)

   var approvals = [
      {type: 'media'},
      {type: 'scope'},
    ]

    var allApprovalTypes = [
      'media',
      'scope',
      'finance',
      'compliance',
    ];

   var hasType = (el) => {
       return el.type === type;
   }

   allApprovalTypes.map((type) => {
        return approvals.find((el)=> el.type === type) || {type: type} // this works.
   });

   allApprovalTypes.map((type) => {
      return approvals.find(hasType) || {type: type} // this wont work.        
   });

2 个答案:

答案 0 :(得分:2)

hasType正在引用其范围中不存在的“类型”变量。你需要内联该函数来获取它(或将它包装在一个闭包中,但这几乎是一样的)

allApprovalTypes.map((type) => {
  return approvals.find((el) => {
       return el.type === type;
   }) || {type: type}
});


   // closure
   var hasType = (type) => (el) => {
       return el.type === type;
   }

P.S。 - 无关,但在ES6中,“{type:type}”可缩短为“{type}”

答案 1 :(得分:0)

您可以使用.bind()。您可以将type(额外参数)传递给回调。

var approvals = [
      {type: 'media'},
      {type: 'scope'},
    ]

    var allApprovalTypes = [
      'media',
      'scope',
      'finance',
      'compliance',
    ];

   var hasType = (el, type) => {
       return el.type === type;
   }

   console.log(allApprovalTypes.map((type) => {
        return approvals.find(hasType.bind(null, type)) || {type: type} // this works.
   }));

   

   //without bind();
   console.log(allApprovalTypes.map((type) => {
        return approvals.find((el) => return hasType(el, type)) || {type: type} // this works.
   }));