分配应用于变量

Assigning apply to a variable

任何人都知道为什么在 javascript 这行得通

m = Math.max
m.apply(null, [1,2,3])

但这不是吗?

m = Math.max.apply
m(null, [1,2,3])

抛出异常:

TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

要理解第二个示例失败的原因,您必须了解 Javascript 中的函数上下文。在 Javascript 中,方法就像发送到被调用对象的消息。它们被调用的对象是它们的上下文,因此这个对象将是函数体内this的值。

apply 是一个特殊函数,它允许您将此上下文设置为第一个参数,然后其余参数将是正在 applied[=20 的函数的参数=] Math.max 在你的例子中。但同时需要在函数对象上调用 apply 才能工作。在第二个示例中,您在 m 变量中存储了对 apply 函数的引用,并且您在没有上下文的情况下调用它,因此它失败了,因为 apply 不知道它必须调用哪个函数。

根据 spec

  1. If IsCallable(func) is false, throw a TypeError exception.

func 是调用 apply 方法的对象。

apply 允许您稍后指定 function 的上下文,在您的情况下是 undefined 因为 m 没有 Function 上下文(应该在参数中指定)。

因为争论

Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

您可以通过尝试以下方法来测试它

示例 1:

m = Math.max.apply.bind(this)
m(this, [1,2,3]) 

Uncaught TypeError: Function.prototype.apply was called on , which is a object and not a function

示例 2:

m = Math.max.apply.bind(null)
m(this, [1,2,3])

Uncaught TypeError: Function.prototype.apply was called on null, which is a object and not a function

示例 3:(由于指定了函数上下文,因此不会出错

m = Math.max.apply.bind(function(){})
m(this, [1,2,3])

undefined

示例 4:(最后这给了你想要的输出)

m = Math.max.apply.bind(Math.max)
m(this, [1,2,3])

3