首页 > 解决方案 > 使用外部范围的部分参数调用 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);
  }
  ...
}

标签: javascriptscopeclosures

解决方案


不知道这是否是您的意思,但是您可以像这样从外部函数的范围传递它们:

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);

推荐阅读