0

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?

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can bind the function to an array of [a, b, c] instead, and then change the property at index 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:

const func1 = (a,b,c) => a + b + c; 
const params = [1, 2];
const func2 = (c) => func1(...params, c);
func2(3);
func2(6);

Comments

0

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

Comments

0

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

You can use this function(arrow): const func2 = () => func1(a, b, c);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.