簡體   English   中英

Javascript 綁定() function

[英]Javascript bind() function

我需要編寫一個接受 function 和 function 和一個參數並返回傳入 function 的綁定版本。 為什么我的代碼不起作用?

function bindToAnArg(func, arg){
 

     let myFunc = func.bind(arg);


return myFunc;

}

////Test

function add(num1, num2) {
  return num1 + num2;
}

const addTwo = bindToAnArg(add, 2);

console.log(addTwo);

const twoPlusSix = addTwo(6);```

bind的第一個參數是調用 function 時this的值。 您可能應該只通過null 這可能會奏效:

function bindToAnArg(func, arg) {
    return func.bind(null, arg);
}

func.bind(...)的第一個參數必須是 function 的上下文 ( this )。 完全避免Function.prototype.bind可能更容易。

 const bind = (f, ...a) => (...b) => f(...a, ...b) const add = (a, b) => a + b const addTwo = bind(add, 2) console.log("2 plus 6 equals", addTwo(6)) // 2 plus 6 equals 8 const addMany = (...all) => all.reduce(add, 0) const addSome = bind(addMany, 1, 2, 3) console.log("1 plus 2 plus 3 plus 4 plus 5 equals", addSome(4, 5)) // 1 plus 2 plus 3 plus 4 plus 5 equals 15

暫無
暫無

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

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