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"
/** www.lsauer.com 2011
* http://www.lsauer.com/2011/08/javascript-using-placeholders-s-d-in.html
*/
var r = (r||{
t : "check",
m : "mate",
c: 10.10
});
console.log('It is '+r.t+r.m+' for Player A. Game Stat:'+r.c);
//By using placeholders, the same example statement can be written more clearly, as follows:
console.log('It is %s%s for Player A. Game Stat: %d',r.t, r.m, r.c);
Source: https://gist.github.com/lsauer/2850506
As Keith said, this is equivalent if not better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.