javascript - 使用外部范围的部分参数调用 javascript 对象方法
问题描述
我有一个 getValidators 函数,它返回一个带有验证器方法的对象:
export function getValidators() {
return {
required: (node, value, [mark='', falsy=[undefined, '']]) => {
const notValid = falsy.includes(value);
return setNotValid(node, notValid, mark);
},
// ... other validator functions ...
};
};
所有验证器函数都有三个参数:节点、值和数组:args
我可以运行验证器功能:
let validator = 'required';
let validators = getValidators()
let result = validators[validator](node, value, args);
但我喜欢使用来自某个外部范围的参数节点和值来运行下面修改后的验证器函数:
export function getValidators() {
return {
required: ([mark='', falsy=[undefined, '']]) => {
const notValid = falsy.includes(value);
return setNotValid(node, notValid, mark);
},
// ...
};
};
并喜欢运行它,如下所示:
// ... node and value args passed in from outer scope ...?
let result = validators[validator](args);
更新:我不能使用getValidators(node, value)
,因为将首先调用 getValidators 以添加其他验证器功能。
let validators = getValidators();
validators[method] = aValidatorFunc;
.....
.....
function runValidators() {
.....
// use the updated validators instance to run the validators
for (let validator of .....) {
// node and value will change in this loop as well
...
let result = validators[validator](args);
}
...
}
解决方案
不知道这是否是您的意思,但是您可以像这样从外部函数的范围传递它们:
export function getValidators(node, value) { // Put them in the argument list here
return {
required: ([mark='', falsy=[undefined, '']]) => {
const notValid = falsy.includes(value);
return setNotValid(node, notValid, mark);
},
//...
};
};
let validator = 'required';
let validators = getValidators(node, value); // Pass your node and value to the outer function
// Now call it like you wanted to call it:
let result = validators[validator](args);
推荐阅读
- swift - Combine`s subscribe(on:options:) 运算符
- clojure - 如何使用 java-time 生成 JWT exp 声明?
- excel - 如何将负数连续向上移动一个单元格并转换为正数,然后删除负数行?
- c - 即使我做对了,C 中矩阵问题的分数也很低?
- tensorflow - 为什么我的 TensorFlow 在第一次运行时收到警告但随后可以工作?
- python - 如何将嵌套的 JSON 展平为 pandas 数据框
- scala - Scala:创建通用集合的问题
- python - 从winsound听不到python中的声音
- jupyter-notebook - 在 Jupyter Lab 中更改 Jupyter 笔记本选项卡自动完成字体颜色?
- vba - 使用 VBA 列出 zip(TAR) 文件的内容