【问题标题】:Why Javascript load into a function "functions as parameters" before than variables?为什么 Javascript 比变量先加载到函数“作为参数的函数”中?
【发布时间】:2014-09-27 20:47:38
【问题描述】:

“fn”console.log 出现在两个变量的 console.log 之前。

我的功能是:

function test1(var1, var2, fn){ 
   console.log(var1, var2);
   fn();
}

function test2(var3){
   console.log(var3 + " it's here");
}

呼叫:

test1(123, "Hello!", test2("Look") );

【问题讨论】:

  • 在调用test1 之前,您需要知道其所有参数的值。 test2("Look") 必须先被评估。
  • @Donovant:不,这并不明显。 -1
  • @LiviuM。如果您阅读了整个问题,您就会看到传递给test1 的参数。
  • @EvanKnowles:从什么时候开始参数名称与传递的变量(/函数)的名称有任何关系?
  • 那为什么还要用神秘的“不,这并不明显。-1”来评论呢?如果你要评论你的否决票,至少就如何改进 Q/A 提出建议,而不是简单地说 “Bad question -1”

标签: javascript function parameter-passing


【解决方案1】:

您没有将函数作为第三个参数传递,而是调用该函数并传递其返回值。应该是:

test1(123, "Hello!", function() { test2("Look"); });

除了得到错误的输出顺序之外,当你尝试调用fn() 时,你也应该得到一个错误,因为fn 是未定义的。

【讨论】:

    【解决方案2】:

    当您致电test1(123, "Hello!", test2("Look") ); 时,会发生以下情况:

    • 执行test2("Look")
    • 将该函数调用的返回值传递给test1test1(123, "Hello!", undefined);

    基本上,test2 在调用test1 之前执行,因为您将函数的返回值作为参数传递。

    要真正传递函数本身,“稍后”执行,您需要将其包装在匿名函数中:

    test1(123, "Hello!", function() { test2("Look"); });
    

    【讨论】:

      【解决方案3】:

      代码应如下所示:

      (function(){
      function test1(var1, var2, fn){ 
         console.log(var1, var2);
         fn("Look");
      }
      
      function test2(var3){
         console.log(var3 + " its here");
      }
      
      test1(123, "Hello!", test2);
      })();
      

      BTW "it's here" - '(单引号)比 "(双引号)更强大。它应该看起来像 'it\'s here' 或 "it\'s here"。

      如果你想调用传递函数,它应该看起来像@Cerbrus 和@Barmar 所说:

      test1(123, "Hello!", function() { test2("Look"); });
      

      【讨论】:

        猜你喜欢
        • 2013-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 1970-01-01
        • 2016-05-01
        • 1970-01-01
        相关资源
        最近更新 更多