Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Param placeholder when using javascript bind function

Tags:

javascript

I can use bind() to bind function and parameters.

For example, outputTwo() needs two parameters. I bind it with a parameter, then I only need to pass one parameter to it on calling. Looks like:

<script>
function outputTwo(param1, param2) {
    console.log(param1, param2);
}
var boundOutput = outputTwo.bind(null, "what"); // the first param should be an object, to replace <this> object in function, which not needed in our question
boundOutput("the heck?");
</script>

It will output What the heck?.

Question is: Can I bind the second parameter to outputTwo(), without binding the first one?

In C++, there is something called placeholders. When I need to bind param2 without binding param1, I need to pass a placeholder to param1, looks like:

auto boundOutput = std::bind(outputTwo, std::placeholders_1, "the heck?");
boundOutput("what");

It will output What the heck?. Is there something like this in javascript?

EDIT: I'm writing a browser extension, and the function I need to bind, is written by me, but called by browser. So I'm not able to change the type of the parameter.

like image 934
zhm Avatar asked Jul 25 '26 17:07

zhm


1 Answers

You can, but it wouldn't be as nice:

const bindLast = (fn, this, ...lastArgs) =>
  (...firstArgs) => fn.call(this, [...firstArgs, ...lastArgs]);

You can do something similar with Function.prototype if you want to make it a method on function objects, I generally dislike doing that.

Usage:

const outputFirst = bindLast(outputTwo, null, "world");
outputFirst("hello"); // "hello world"
like image 160
Madara's Ghost Avatar answered Jul 27 '26 05:07

Madara's Ghost