javascript - 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
工作。说如果jobFn
与Curried add(3)
一起传递,那么DoTheJob
将执行 UncurriedAdd of add(3, 6)
; 如果 thenjobFn
是用Curried multiple(5)
传递的,那么DoTheJob
会做 Uncurried 的multiple(5, 6)
;
解决方案
只需将传递的函数分配给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');
推荐阅读
- firebase - Firebase 即时用户禁用?
- calayer - 通过 AVAssetExportSession 导出时,CABasicAnimation 不更新自定义 CALayer 属性
- scala - Scala Recursive For Comprehension 只在空列表前面添加一次,为什么?
- ios - 在 SwiftUI 表单中有多个列
- ios - Flutter 应用程序是否支持 Microsoft Intune App SDK?
- opencv - 没有规则使目标'-L/usr/local/lib'
- linux-kernel - 内核缓冲区和缓存使用 RAM 时使用的 Linux SWAP 内存
- sql - 必须使数据库中的所有现有 GUID 再次唯一。是否有数学运算可以做到这一点?
- javascript - 使用javascript拖放在两个div元素之间插入占位符
- android - Delphi Android:无法捕获鼠标滚轮事件