自我调用功能 [英] self-invoking functions

查看:111
本文介绍了自我调用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编码时:

  var a = 
function()
{
alert(44)
返回函数(){alert(33)}
}()();

这个表达式是按照以下顺序评估的吗?


  1. 定义函数;
  2. 将其引用指针传递给
  3. a()被调用
  4. >
  5. 返回一个新的函数指针

  6. a()被再次调用


    如果是这样,为什么我会有语法错误:

    $ p $ function()
    {
    alert(44)
    return function(){alert(33)}
    }();

    解释器首先需要一个左操作数...

    $ p








    $ alert(44)
    return function(){alert(33)}
    };

    )()
    pre>

    外括号是什么意思???

    谢谢

    解决方案

    这是语言的语法。如果你想就地执行一个匿名函数,你必须把它放在parens中。



    JS有这些边缘情况,其语法比你期望的更为奇怪。举例来说,评估具有JSON的字符串不起作用,除非它用parens包装。

      //错误
    eval({...});
    // Right
    eval(({...}));

    这是该语言的语法。



    这就是说,我认为(这是严格的恕我直言),你列出的步骤是不准确的。


    1. 函数被定义和调用。警报( 44);结果发生。

    2. 该函数返回另一个也被调用的函数。警报( 33);发生。

    3. 最内层的函数不会返回任何东西,所以a实际上是未定义的。 typeof a returnsundefined。


    when I code:

    var a =
    function()
    {
        alert("44")
        return function(){alert(33)}
    }()();
    

    is this expression evaluated in the following order?

    1. define the function;
    2. pass its reference pointer to a
    3. a() is invoked
    4. return in a a new function pointer
    5. a() is invoked again

    and if so why do I have a syntax error if I do:

    function()
    {
        alert("44")
        return function(){alert(33)}
    }();
    

    the interpreter wants a left operand first...

    but this syntax works:

    (
      function()
      {
        alert("44")
        return function(){alert(33)}
      };
    
    )()
    

    the outer parenthesis what does meaning???

    Thanks

    解决方案

    It's the syntax of the language. If you want to in-place execute an anonymous function, you must enclose it in parens.

    JS has these edge cases where the syntax is weirder than you expect. Take for example, evaling a string that has a JSON doesn't work unless it's wrapped with parens.

    // Wrong
    eval("{ ... }");
    // Right
    eval("({ ... })");
    

    It's the syntax of the language.

    That said, I think (and this is strictly IMHO), the steps you've outlined are not accurate.

    1. Function is defined and invoked. alert("44"); happens as a result.
    2. The function returns another function which is also invoked. alert("33"); happens.
    3. The innermost function doesn't return anything, so a is effectively undefined. typeof a returns "undefined".

    这篇关于自我调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆