自我调用功能 [英] self-invoking functions
问题描述
当我编码时:
var a =
function()
{
alert(44)
返回函数(){alert(33)}
}()();
这个表达式是按照以下顺序评估的吗?
- 定义函数;
- 将其引用指针传递给
- a()被调用
>
- 返回一个新的函数指针
- a()被再次调用
如果是这样,为什么我会有语法错误:
$ p $function()
{
alert(44)
return function(){alert(33)}
}();
解释器首先需要一个左操作数...
$ p
$ alert(44)
return function(){alert(33)}
};
)()
pre>
外括号是什么意思???
谢谢
解决方案这是语言的语法。如果你想就地执行一个匿名函数,你必须把它放在parens中。
JS有这些边缘情况,其语法比你期望的更为奇怪。举例来说,评估具有JSON的字符串不起作用,除非它用parens包装。
//错误
eval({...});
// Right
eval(({...}));
这是该语言的语法。
这就是说,我认为(这是严格的恕我直言),你列出的步骤是不准确的。
- 函数被定义和调用。警报( 44);结果发生。
- 该函数返回另一个也被调用的函数。警报( 33);发生。
- 最内层的函数不会返回任何东西,所以a实际上是未定义的。 typeof a returnsundefined。
when I code:
var a = function() { alert("44") return function(){alert(33)} }()();
is this expression evaluated in the following order?
- define the function;
- pass its reference pointer to a
- a() is invoked
- return in a a new function pointer
- 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.
- Function is defined and invoked. alert("44"); happens as a result.
- The function returns another function which is also invoked. alert("33"); happens.
- The innermost function doesn't return anything, so a is effectively undefined. typeof a returns "undefined".
这篇关于自我调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!