【问题标题】:What is the purpose of JavaScript's apply() in this case?javascript 的 Apply() 问题
【发布时间】:2011-06-06 00:35:03
【问题描述】:

我研究了以下代码来记录

console.log.apply( console, arguments );

apply() 这里的目的是什么?

为什么不只是console.log("message", arguments)

谢谢。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    apply() 函数使用给定的this 值调用另一个函数,arguments 作为数组提供。

    隐式func.apply(obj, args) 的原因是确保在func() 内,this 引用obj

    【讨论】:

      【解决方案2】:
      console.log("message", arguments)
      

      使用两个参数调用log,“消息”和类似数组的对象参数。

      console.log.apply( console, arguments );
      

      使用n 参数调用它,其中n 是类数组对象参数的长度。换句话说,参数被展开为单独的参数。该方法的上下文是console。例如:

      function foo(a, b, c)
      {
        console.log.apply( console, arguments );
      }
      foo(1,2,3);
      

      大致相当于:

      console.log(1,2,3);
      

      【讨论】:

      • 为了兼容IE9 console.log.apply(console, arguments);可以改成Function.prototype.apply.call(console.log, console, arguments);
      【解决方案3】:

      我认为这两个答案都没有解释为什么。真正闪亮地使用这种编程方式。

      我不喜欢第一个投票的答案,我连读三次都无法理解,第二个感觉不完整。

      我认为编写这种方式的主要目的是在函数(或闭包)中使用它。

      因此,此行仅在您的自定义记录器中有意义:console.log.apply(console, arguments);

      可能是比这样写更好的方法:

      function my_worse_way_to_log_dynamic_args ( [several dynamic arguments] )
      {
          // loop each argument
          // call console.log for each one
      }
      
      function my_better_way_to_log_dynamic_args ( [several dynamic arguments] )
      {
          console.log.apply( console, arguments );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-31
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多