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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With