为什么Function.prototype.apply.call(Math.floor, undefined, [1.75])等价于Math.floor.apply(undefined, [1.75])?
为什么Function.prototype.apply.call(Math.floor, undefined, [1.75])等价于Math.floor.apply(undefined, [1.75])?
在 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` 值在这个调用中并不重要。
6 回答5.5k 阅读✓ 已解决
9 回答9.6k 阅读
5 回答3.8k 阅读✓ 已解决
3 回答10.7k 阅读✓ 已解决
4 回答8.2k 阅读✓ 已解决
7 回答10.2k 阅读
4 回答7.6k 阅读
1.Function.prototype.apply.call(Math.floor, undefined, [1.75]):
2.Math.floor.apply(undefined, [1.75]):
补充
流程图