简体   繁体   English

使用JavaScript中的参数保存对函数的引用

[英]Save reference to a function with parameters in JavaScript

I am calling a function at several places within my app. 我正在应用程序中的多个位置调用函数。 This function takes several parameters whose values might change. 此函数采用多个参数,其值可能会更改。 To avoid re-typing, I want to save a reference to this function so that I can simply call this referred function everywhere. 为了避免重新键入,我想保存对此函数的引用,以便可以在任何地方简单地调用此引用的函数。 Here is the simplified code: 这是简化的代码:

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!

How can I ge func1 to be executed with updated values of a , b and c by calling func2 ? 如何通过调用func2 func1与更新的abc值一起执行?

Use arrow function: 使用箭头功能:

 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()); 

You can bind the function to an array of [a, b, c] instead, and then change the property at index 2: 您可以将函数绑定到[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();

If you only change c , you could consider binding the function to a and b , and then passing the changing c : 如果仅更改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);

If you want to use params from scope where you declare your function, just skip those params in function signature 如果要使用声明函数的作用域中的参数,只需跳过函数签名中的那些参数

 const f = () => a + b + c; let a = 1, b = 2, c = 3; console.log(f()); c = 6; console.log(f()); 

Instead of this const func2 = func1.bind(this, a, b, c); 代替此const func2 = func1.bind(this, a, b, c);

You can use this function(arrow): const func2 = () => func1(a, b, c); 您可以使用此函数(箭头): const func2 = () => func1(a, b, c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM