【问题标题】:What is the difference between calling a function with call/apply or directly?使用 call/apply 或直接调用函数有什么区别?
【发布时间】:2020-08-18 19:44:50
【问题描述】:

我知道通过调用 apply 您可以从函数中访问不同的 this 属性,但在这种特定情况下,我不知道为什么它们会有所不同。无论如何,'this'不会来自同一个地方(项目)吗?

这个原始代码不起作用:

_.invoke = function (collection, methodName) {

    var slicedArgs = Array.prototype.slice.call(arguments, 2);

    return _.map(collection, (item) => {
        if (typeof methodName === "string") {
            return item[methodName](slicedArgs);
        } else {
            return methodName.apply(item, slicedArgs);
        }
    });
};

当我更改地图函数内部的内容时,它运行良好:

_.invoke = function (collection, methodName) {
    var slicedArgs = Array.prototype.slice.call(arguments, 2);

    return _.map(collection, (item) => {
        if (typeof methodName === "string") {
            return item[methodName].apply(item, slicedArgs);
        } else {
            return methodName.apply(item, slicedArgs);
        }
    });
};

那么与 apply 有什么关系呢?我的第一个代码中的“this”绑定是什么,第二个代码发生了什么变化?

【问题讨论】:

  • 第一个是method([1,2,3]),apply把数组展开到每个参数位置,变成method(1,2,3)
  • 哇,我不敢相信我花了这么长时间。谢谢你,安迪,你让我的大脑免于爆炸!

标签: javascript function underscore.js apply


【解决方案1】:

在第一个示例中,您缺少 ... 将您的 slicedArgs 数组传播到多个参数中,因此您将数组本身作为单个参数传递。如果您将代码更改为return item[methodName](...slicedArgs),它将起作用。

它与apply 一起工作的原因是apply 接受一个array 参数。

【讨论】:

  • 感谢 CherryDT!在此之前我从未真正使用过调用、应用或绑定,所以我完全忘记了我需要传播 args。
猜你喜欢
  • 2015-11-03
  • 2012-01-01
  • 2017-03-31
  • 2014-05-02
  • 2021-08-29
  • 2011-12-11
  • 2014-03-16
  • 2012-06-02
相关资源
最近更新 更多