使用预填充参数从其他函数创建函数

问题描述 投票:1回答:3

是否可以创建一个与另一个函数相同但具有预先给定参数的函数。就像是

function f(x){
  return x
}
var f2 = //f(2);
console.log(f2()); //Should print 2

我知道这在OcamL中有点可能,所以我想知道我是否可以在JS中做到这一点。另一种方法是做

var f2 = function(){f(2)};
f2();

但我不知道这是多么违法,如果我不敢嫌监狱。

javascript ecmascript-6
3个回答
3
投票

选项1 - 创建一个包装函数,该函数返回使用f()调用2的结果。

function f(x){
  return x
}

var f2 = () => f(2);

console.log(f2()); //Should print 2

选项2 - 使用Function.bind()prepended arguments

function f(x){
  return x
}

var f2 = f.bind(null, 2);

console.log(f2()); //Should print 2

1
投票

只需使f2成为一个函数,用你想要的任何东西调用f,然后将调用的结果返回给f

var f2 = function() {
    return f(2);
};

0
投票

您需要在函数中创建一个函数。

function f(x)
{
  return function() {
    return x;
  };
}

var f2 = f(2),
    f3 = f(3),
    f4 = f(4);

console.log("f2: " + f2());
console.log("f3: " + f3());
console.log("f4: " + f4());
© www.soinside.com 2019 - 2024. All rights reserved.