javascript - 在JavaScript中,将引用保存到有参数的函数中

下面是简化的代码:


const func1 = (a,b,c) => a + b + c; 


let a = 1, b = 2, c = 3;


const func2 = func1.bind(this, a, b, c);


func2();


//prints 6


c = 6;


func2();


//still prints 6!



如何通过调用func2,通过abc更新func1来执行?

时间:


const func1 = (a,b,c) => a + b + c; 


let a = 1, b = 2, c = 3;


const func2 = () => func1(a, b, c);


console.log(func2());


c = 6;


console.log(func2());

可以将该函数绑定到[a, b, c]数组,然后在索引2处更改该属性:


const func1 = (a,b,c) => a + b + c; 


const params = [1, 2, 3];


const func2 = () => func1(...params);


func2();


params[2] = 6;


func2();



如果只更改c,则可以考虑将函数绑定到ab,然后传递更改的c


const func1 = (a,b,c) => a + b + c; 


const params = [1, 2];


const func2 = (c) => func1(...params, c);


func2(3);


func2(6);



你可以为此创建一个闭包: 请尝试以下操作:


function calc(a){


 return b=> c => a+b+c;


}


let a = 1, b = 2, c = 3;



console.log(calc(a)(b)(c));


c = 6;


console.log(calc(a)(b)(c));



// Or fix two values and make third variable



let calc2 = calc(1)(2);



console.log(calc2(5));


console.log(calc2(7));


console.log(calc2(9));

如果要在声明函数的范围中使用params,只需跳过函数签名中的那些参数,


const f = () => a + b + c;


let a = 1, b = 2, c = 3;


console.log(f());


c = 6;


console.log(f());

用这个替代const func2 = func1.bind(this, a, b, c);

你可以使用这个功能(=>):const func2 = () => func1(a, b, c);

...