gpt4 book ai didi

javascript - javascript iffy结构之间的区别

转载 作者:行者123 更新时间:2023-12-03 06:52:01 24 4
gpt4 key购买 nike

这些js函数结构有什么区别

(function () { console.log("Foo!"); }());

(function () { console.log("Foo!"); })();

;(function () { console.log("Foo!"); }());

+function() { console.log("done!"); }();

最佳答案

据我所知,前三个没有区别。

当您编写立即调用函数表达式时,外部参数括号可以存在于包装括号的内部和外部。将其视为具有相同目的的另一种语法。

所以这个:

(
function() {
}
());

还有这个:

(
function() {
}
)();

完全平等。

对于第三个示例,分号,在文件串联的情况下用作保护措施。当您编写代码时,您或 vendor 可能有一个不以分号结尾的脚本。在这种情况下,当您连接不以问号结尾的先前文件代码时,脚本将会中断。

示例

script-1.js

var name = 'Nikos';
console.log( name )

script-2.js

(
function() {
// Do some stuff here
}
)();

concatenation.js

var name = 'Nikos';
console.log( name ) // This line will throw an error, because it is not the last statement in the file.

(
function() {
// Do some stuff here
}
)();

但是如果我们将 script-2.js 更改为:

script-2.js

;(
function() {
// Do some stuff here
}
)();

concatenation.js 将如下所示:

var name = 'Nikos';
console.log( name )

;( // This will force the previous statement to finish.
function() {
// Do some stuff here
}
)();

最后我发现了这个:

It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:

+function() { console.log("Foo!"); }();

Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.

  • is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());

来自:https://stackoverflow.com/a/13341710/1150619

关于javascript - javascript iffy结构之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com