簡體   English   中英

使用來自外部作用域的部分參數調用 javascript 對象方法

[英]call javascript object method using partial arguments from outer scope

我有一個 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);

使用bind(this)找到了一種解決方案:

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
     ...
     const validatorFunc = validators[validator].bind({node, value})  // bind this
     // or with call with a given this as firtst argument: 
     // const validatorFunc = validators[validator].call({node, value}, args); 

     let result = validatorFunc(args);
  }
  ...
}

使用 bind 我們不能使用箭頭函數,所以要使用“this”:

export function getValidators()  {

  return {
    required: function([mark='', falsy=[undefined, '']]) {  // function
      const notValid = falsy.includes(this.value);
      return setNotValid(this.node, notValid, mark);
    },
    // ...
  };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM