Files
scottyah-blog/hugo-content/themes/cactus/exampleSite/content/posts/2019-03-08-es6-bind-trick.md
2022-07-31 17:32:45 -07:00

1.2 KiB

title, date, tags, category, keywords
title date tags category keywords
Bind specific arguments of a function 2019-03-08 09:00:00
JavaScript
tech
Javascript
ES2015
ES6

To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind():

function func(p1, p2, p3) {
    console.log(p1, p2, p3);
}
// the binding starts after however many are passed in.
function decorator(...bound_args) {
    return function(...args) {
        return func(...args, ...bound_args);
    };
}

// bind the last parameter
let f = decorator("3");
f("a", "b");  // a b 3

// bind the last two parameter
let f2 = decorator("2", "3")
f2("a");  // a 2 3

Even if we want to bind just the nth argument, we can do as follows:

// bind a specific (nth) argument
function decoratorN(n, bound_arg) {
    return function(...args) {
        args[n-1] = bound_arg;
        return func(...args);
    }
}

let fN = decoratorN(2, "2");
fN("a","b","c"); // a 2 c

https://stackoverflow.com/questions/27699493/javascript-partially-applied-function-how-to-bind-only-the-2nd-parameter