首页 > 解决方案 > ES6 传递函数作为参数示例

问题描述

我不太了解 JS/ES6,无法用代码描述我的问题。所以这个问题的大部分是概念上和伪代码。

假设我有这样的Contractor课程:

class Contractor {
 constructor(jobFn) {
    // save jobFn;
  }

  dailyRoutine() {
    // let result = DriveToWork()
    const result = 6
    DoTheJob(result)
    DriveBackHome()
  }

}

问题是,DoTheJob()在不同的地方可能会做不同的事情。

所以在地方 A,它可能是

he = new Contractor(write_front_end(with, this, and that))

在地方 B,它可能是

he = new Contractor(fix_backend_node(with, express))

即,行为需要在构造函数期间传入,并且动作可能需要采用不同种类和不同数量的参数。

ES6 能做到这样吗?
请展示 ES6 代码,该代码可以通过构造函数将具有不同种类和不同数量参数的函数传递给DoTheJob().

此外,挑战在于jobFn需要一个Curried函数,这意味着缺少一个或多个参数来完成这项DoTheJob工作。说如果jobFnCurried add(3)一起传递,那么DoTheJob将执行 UncurriedAdd of add(3, 6); 如果 thenjobFn是用Curried multiple(5)传递的,那么DoTheJob会做 Uncurried 的multiple(5, 6)

标签: javascriptlambdaecmascript-6functional-programming

解决方案


只需将传递的函数分配给this.DoTheJob,然后this.DoTheJob在里面调用dailyRoutine

class Contractor {
  constructor(jobFn) {
    this.DoTheJob = jobFn;
  }
  dailyRoutine() {
    // DriveToWork()
    this.DoTheJob();
    // DriveBackHome()
  }
}

const c1 = new Contractor(() => console.log('doing job A'));
c1.dailyRoutine();

const c2 = new Contractor(() => console.log('doing job B'));
c2.dailyRoutine();

// c1 again:
c1.dailyRoutine();

// feel free to reference any in-scope variables in the passed function,
// no need to pass the variables as additional parameters
const data = 'data';
const c3 = new Contractor(() => console.log('data is', data));
c3.dailyRoutine();

如果dailyRoutine需要使用需要发送到传递doTheJob函数的数据来调用,只需在传递的函数中定义所需的参数,这里不需要实际的柯里化:

class Contractor {
  constructor(jobFn) {
    this.DoTheJob = jobFn;
  }
  dailyRoutine(doJobArg) {
    this.DoTheJob(doJobArg);
  }
}

// feel free to reference any in-scope variables in the passed function,
// no need to pass the variables as additional parameters
const data = 'data';
const c3 = new Contractor((arg) => console.log('data is', data, 'and arg is', arg));
c3.dailyRoutine('argDoTheJobIsCalledWith');


推荐阅读