请教一个call和apply的问题?

为什么Function.prototype.apply.call(Math.floor, undefined, [1.75])等价于Math.floor.apply(undefined, [1.75])?

阅读 675
avatarAI BotBETA
在 JavaScript 中,`Function.prototype.apply` 和 `Function.prototype.call` 是两个用于调用函数的方法,它们允许你显式地设置函数内部的 `this` 值,并且以数组(对于 `apply`)或参数列表(对于 `call`)的形式传递参数。

表达式 `Function.prototype.apply.call(Math.floor, undefined, [1.75])` 可以分解为以下几个步骤来理解其等价性:

1. **`Function.prototype.apply`** 是一个函数,它的第一个参数是 `thisArg`(即函数体内 `this` 的值),第二个参数是一个数组或类数组对象,表示被调用函数的参数。

2. **`Function.prototype.apply.call(...)`**:这里使用了 `call` 方法来调用 `apply` 函数。`call` 的第一个参数指定了 `apply` 函数内部 `this` 的值,即 `Math.floor`。`call` 的第二个参数是 `undefined`(在这个上下文中,对于 `Math.floor` 这样的函数,`this` 值是无关紧要的,因为 `Math.floor` 不使用其 `this` 值),第三个参数是 `[1.75]`,它将被传递给 `Math.floor` 作为参数。

3. 因此,`Function.prototype.apply.call(Math.floor, undefined, [1.75])` 实际上是在说:“使用 `apply` 方法以 `Math.floor` 作为 `this` 值,并传递 `undefined` 作为 `thisArg`(对于 `Math.floor` 来说不重要),以及 `[1.75]` 作为参数数组来调用 `Math.floor`”。

4. 简化来看,`Function.prototype.apply.call(Math.floor, undefined, [1.75])` 直接等价于 `Math.floor.apply(undefined, [1.75])`,因为两者都是在调用 `Math.floor` 函数,传递相同的参数数组 `[1.75]`,并且 `Math.floor` 的 `this` 值在这个上下文中是无关紧要的。

5. 进一步简化,由于 `Math.floor` 不依赖于其 `this` 值,所以 `Math.floor.apply(undefined, [1.75])` 等价于 `Math.floor(1.75)`,结果都是 `1`。

总结来说,`Function.prototype.apply.call(Math.floor, undefined, [1.75])` 等价于 `Math.floor.apply(undefined, [1.75])`,是因为两者在函数调用和参数传递上是一致的,而 `Math.floor` 的 `this` 值在这个调用中并不重要。
1 个回答

1.Function.prototype.apply.call(Math.floor, undefined, [1.75]):

  • Function.prototype.apply 是 apply 方法的原型。
  • call 方法调用 apply 方法,并将 Math.floor 作为 this 值传递给 apply 方法。
  • 然后,apply 方法调用 Math.floor,并将 undefined 作为 this 值传递,同时传递参数 [1.75]。
  • 结果同样是 Math.floor(1.75),返回 1。

2.Math.floor.apply(undefined, [1.75]):

  • Math.floor 是一个函数。
  • apply 方法调用 Math.floor,并将 undefined 作为 this 值传递,同时传递参数 [1.75]。
  • 结果是 Math.floor(1.75),返回 1。

补充

流程图

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏