darKnight
darKnight

Reputation: 6481

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?

Upvotes: 0

Views: 193

Answers (4)

Varun Raval
Varun Raval

Reputation: 134

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

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

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

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

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

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

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 370739

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

Upvotes: 0

Related Questions