使用JavaScript的bind函数时,参数占位符是什么?

3
我可以使用 bind() 来绑定函数和参数。
例如,outputTwo() 需要两个参数。我使用一个参数来绑定它,然后在调用时只需要传递一个参数即可。看起来像这样:
<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>

它将输出什么鬼?

问题是:我能否将第二个参数绑定到outputTwo(),而不绑定第一个参数?

在C ++中,有一种称为占位符的东西。当我需要绑定param2而不绑定param1时,我需要将占位符传递给param1,看起来像:

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

它将输出What the heck?,在javascript中是否有类似的内容?

编辑: 我正在编写一个浏览器扩展,需要绑定的函数是由我编写的,但是由浏览器调用。因此,我无法更改参数的类型。


2
给出反对意见的人:请解释一下为什么?这似乎是一个合理的问题。 - mplungjan
确实,你的问题没有任何问题。阐述得很清楚。回到答案,bind将按从左到右的顺序进行处理。但是JavaScript中一个很好的特性是对象字面量,如果使用这些字面量,您可以创建更复杂的默认参数。{first:"one"}并具有从调用方便自我记录代码的优点。 - Keith
2个回答

1

你可以这样做,但效果不会那么好:

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

如果您想将其作为函数对象的方法,可以使用Function.prototype实现类似功能,但我通常不喜欢这样做。

用法:

const outputFirst = bindLast(outputTwo, null, "world");
outputFirst("hello"); // "hello world"

-1
/** 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);

来源:https://gist.github.com/lsauer/2850506

正如Keith所说,这是等效的,如果不是更好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接