Bind specific arguments of a function
To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind()
:
1function func(p1, p2, p3) {
2 console.log(p1, p2, p3);
3}
4// the binding starts after however many are passed in.
5function decorator(...bound_args) {
6 return function(...args) {
7 return func(...args, ...bound_args);
8 };
9}
10
11// bind the last parameter
12let f = decorator("3");
13f("a", "b"); // a b 3
14
15// bind the last two parameter
16let f2 = decorator("2", "3")
17f2("a"); // a 2 3
Even if we want to bind just the nth argument, we can do as follows:
1// bind a specific (nth) argument
2function decoratorN(n, bound_arg) {
3 return function(...args) {
4 args[n-1] = bound_arg;
5 return func(...args);
6 }
7}
8
9let fN = decoratorN(2, "2");
10fN("a","b","c"); // a 2 c