【问题标题】:Javascript difference between calling a function directly and using applyJavascript直接调用函数和使用apply的区别
【发布时间】:2015-11-03 05:53:46
【问题描述】:

两者都在相同的上下文中调用相同的函数,那么这些语句之间有什么区别。

this.subject.hello();

apply() 用于在不同的上下文中调用方法。但在这里它是在相同的上下文中调用的。

this.subject.hello.apply(this.subject, arguments)

【问题讨论】:

  • apply 不会改变“上下文”,它用于将函数的 this 的值设置为特定值。

标签: javascript


【解决方案1】:

第一个调用它没有参数。第二个使用当前函数的参数调用它。

this.subject = {
  hello: function() {
    console.log("Hello called with arguments " + JSON.stringify(arguments));
  }
};

function callHello() {
  console.log("this.subject.hello();");
  this.subject.hello();
  console.log("this.subject.hello.apply(this.subject, arguments);");
  this.subject.hello.apply(this.subject, arguments);
}

callHello(1, 2);
// => this.subject.hello();
//    Hello called with arguments {}
//    this.subject.hello.apply(this.subject, arguments);
//    Hello called with arguments {"0":1,"1":2}

【讨论】:

  • 我也可以传递第一个中的参数。
  • 一般来说,当你不知道你会有多少个参数时,你会使用apply来调用函数/方法。一个常见的例子是破坏性地连接一个数组:concat 返回一个新数组,但如果你想通过修改现有数组来连接,你可以使用push:array.push(3, 4)。但是如果你有两个数组,你就不能使用array.push(other);说array.push(other[0], other[1]) 是愚蠢的,因为你需要知道它永远不会有超过2 个成员,你不能使用array.push(*other) 的Ruby splat 技巧;所以你需要申请apply:array.push.apply(array, other)
【解决方案2】:

唯一的区别是在第一次调用中你没有传入任何参数。

【讨论】:

    【解决方案3】:

    使用apply我们可以改变方法的上下文,通常它需要当前对象的上下文。 context 作为第一个参数传递是 apply 方法,其他参数在数组中传递,这是 apply 方法的第二个参数。

    callapply之间的其他查询可以参考 Stackoverflow question : What is the difference between call and apply?

    【讨论】:

    • "通常需要当前对象的上下文"。没有。函数的 this 由调用设置,它与当前(执行)上下文无关。许多函数在没有设置 this 的情况下被调用,因此它默认为全局对象或在严格模式下为 undefined
    【解决方案4】:

    唯一的区别是一个带有arguments而另一个没有。

    【讨论】:

      【解决方案5】:

      以下是关于applycall 和 JavaScript 上下文主题的一些很好的答案:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-28
        • 2012-01-01
        • 2017-03-31
        • 2013-07-17
        • 2012-08-16
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        相关资源
        最近更新 更多