【问题标题】:Param placeholder when using javascript bind function使用 javascript 绑定函数时的参数占位符
【发布时间】:2016-10-31 07:56:10
【问题描述】:

我可以使用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>

它将输出What the heck?。

问题是:我可以将第二个参数绑定到outputTwo(),不绑定第一个参数吗?

在 C++ 中,有一个叫做placeholders 的东西。当我需要绑定param2而不绑定param1时,我需要将placeholder传递给param1,看起来像:

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

它将输出What the heck?。 javascript中有这样的东西吗?

编辑: 我在写一个浏览器扩展,我需要绑定的功能,是我自己写的,浏览器调用的。所以我无法更改参数的类型。

【问题讨论】:

  • 反对者:请解释原因?这似乎是一个合理的问题。
  • 确实,你的问题没有错。解释得很好。无论如何,对于答案,绑定只会从左到右。但是 JS 的一个巧妙特性是对象字面量,如果您通过使用这些字面量,您可以创建更复杂的默认参数。 {first:"one"} 并且具有从被调用方创建自我记录代码的优势。

标签: javascript


【解决方案1】:

你可以,但不会那么好:

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

如果你想让Function.prototype 成为函数对象的方法,你可以做类似的事情,我一般不喜欢这样做。

用法:

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

【讨论】:

    【解决方案2】:
    /** 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 所说,即使不是更好,这也是等效的。

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多