我想用一些参数创建回调函数,但我希望其中的一个值永远不会改变,并在创建函数时设置!
p.e.
let a = 2;
let y = (b) => { let staticValue = a; return staticValue * b; }
y(1) => 2 -> OK
然后
a = 3
y(1) => 3 -> Not OK -> I want the function to have the original value of a.
我知道,之所以会发生这种情况,是因为只有在调用函数时才会对变量a求值。但有什么变通办法吗?
您可以使用所谓的IIFE(立即调用的函数表达式(来实现这一点
let a = 2;
const y = (staticValue => b => staticValue * b)(a);
a = 44;
console.log(y(1));
这里发生的事情是,你有两个函数。第一个,staticValue => ...
被立即调用,并且staticValue
被赋予a
的值。由于a
是IIFE的参数,因此一旦调用函数,即使a
的值发生了变化,staticValue
也不会发生变化。
第一个函数的返回值是第二个函数b=> ...
。
let a = 2
let makeY = () => {
let staticValue = a;
return (b)=> staticValue * b;
}
let y = makeY();
或
let a = 2
let y = ((staticValue, b) => {
return staticValue * b;
}).bind(null, a)
您可以使用闭包
function first (a) {
function second (b) {
return a * b;
}
return second;
}
let x = first(2) // the inner function second will close around the variable a which is 2 in this case
console.log(x(3))
let y = first(5) // the inner function second will close around the variable a which is 5 in this case
console.log(y(3))
我认为您可以应用函数式编程方法。
const getYFn = (a , b) => {
return a * b;
}
const a = 2
const y = getYFn.bind(null, a);
// the constant y now is a function that partially applied first param
console.log(y(1)); // 2
console.log(y(3)); // 6