Function.prototype.apply.bind用法?

Roy*_*mir 15 javascript

我非常清楚以下用法:

Function.prototype.bind.apply(f,arguments)

说明-使用原始(如果存在的话)bind方法在farguments(其中它的第一项将被用作上下文this)

此代码可用于(例如)通过带参数的构造函数创建新函数

示例:

function newCall(Cls) {
    return new (Function.prototype.bind.apply(Cls, arguments));
 }
Run Code Online (Sandbox Code Playgroud)

执行:

var s = newCall(Something, a, b, c);
Run Code Online (Sandbox Code Playgroud)

我遇到了这个:Function.prototype.apply.bind(f,arguments)//单词交换

题 :

因为很难理解它的含义 - 在什么用法/场景中我会使用这个代码?

xda*_*azz 30

这用于修复第一个参数.apply.

例如,当您从数组中获取最大值时,您可以:

var max_value = Math.max.apply(null, [1,2,3]);
Run Code Online (Sandbox Code Playgroud)

但是你想要修复第一个参数null,所以你可以通过以下方式创建一个新函数:

var max = Function.prototype.apply.bind(Math.max, null);
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

var max_value = max([1,2,3]);
Run Code Online (Sandbox Code Playgroud)

  • **非常好的例子 (4认同)
  • 为什么将bind作为参数传递给null很重要? (3认同)