是否可以创建一个与另一个函数相同但具有预先给定参数的函数。就像是
function f(x){
return x
}
var f2 = //f(2);
console.log(f2()); //Should print 2
我知道这在OcamL中有点可能,所以我想知道我是否可以在JS中做到这一点。另一种方法是做
var f2 = function(){f(2)};
f2();
但我不知道这是多么违法,如果我不敢嫌监狱。
选项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
只需使f2
成为一个函数,用你想要的任何东西调用f
,然后将调用的结果返回给f
:
var f2 = function() {
return f(2);
};
您需要在函数中创建一个函数。
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());