使用javascript绑定函数时的参数占位符

使用javascript绑定函数时的参数占位符,javascript,Javascript,我可以使用bind()绑定函数和参数 例如,outputwo()需要两个参数。我用一个参数绑定它,然后我只需要在调用时向它传递一个参数。看起来像: <script> function outputTwo(param1, param2) { console.log(param1, param2); } var boundOutput = outputTwo.bind(null, "what"); // the first param should be an object, t

我可以使用
bind()
绑定函数和参数

例如,
outputwo()
需要两个参数。我用一个参数绑定它,然后我只需要在调用时向它传递一个参数。看起来像:

<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>
auto boundOutput = std::bind(outputTwo, std::placeholders_1, "the heck?");
boundOutput("what");
它将输出
到底是什么?
。javascript中有类似的东西吗

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

/** 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);
资料来源:


正如基思所说,如果不是更好的话,这是相当的。

你可以这样做,但这并没有那么好:

const bindLast = (fn, this, ...lastArgs) =>
  (...firstArgs) => fn.call(this, [...firstArgs, ...lastArgs]);
你可以用
Function.prototype
做一些类似的事情,如果你想让它成为函数对象上的一种方法,我通常不喜欢这样做

用法:

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

选民:请解释为什么?这似乎是一个合理的问题。事实上,你的问题没有错。解释得很好。不管怎么说,bind的答案是从左到右。但是JS的一个整洁的特性是对象文字,如果您使用这些文字传递,您可以创建更复杂的默认参数<代码>{first:“one”}并且具有从被调用方创建自文档代码的优势。