有人能为我解释一下JS文件中的以下函数吗?
function Init()
{
(function set()
{
-----code---
print "hello";
}
)();
}
如果我调用Init函数,它会自动运行设置为函数的set()函数吗?还是我需要调用set()来运行它?
有人能为我解释一下JS文件中的以下函数吗?
function Init()
{
(function set()
{
-----code---
print "hello";
}
)();
}
你需要调用 Init
来运行其中的任何代码。现在,里面的代码只是普通的 JavaScript 代码,但是它很有趣。让我们看看为什么。
你的内部函数被称为所谓的IIFE。为了使外部函数(Init
)更易读,你可以用IIFE调用的结果替换内部函数。
以下是一些示例:
var x = undefined; // x === undefined
x = (undefined); // again
x = 3; // x === 3
x = (3); // again the same
x = 'some string'; // some string
x = ('some string'); // the same
所以,在对象周围放置()
是可以的,你会得到相同的对象。对于函数也是一样。
x = function() {}; // x is that function now.
x = (function() {}); // the same.
x = 3;
,你能调用 x 吗?
x = 3;
x(); // syntax error
x = (3);
x(); // again error. can't call a number.
x = function() { console.log('Hi'); }; // you can call x now.
x(); // logs 'Hi'!
如果你使用括号做同样的事情,结果是相同的:
x = (function() { console.log('Hi'); }); // again, the same.
x(); // no error, function called again!
// instead of x = (...); and the x(), you replace the x part right away.
(function() { console.log('Hi'); })()
// function body up to here ^^ now the call part.
function() { console.log('Hi'); }(); // syntax error.
()
放在那个函数表达式周围,只是为了将其转换为一个对象。
这就是它的工作原理。 但为什么? 因为你想要确保没有其他人调用你的函数!如果你这样做:
var x = function() {};
x();
+
,-
或!
,如!function(){}()
。;-) - RobG这是 JavaScript 中的基本函数闭包(一个内部函数在另一个函数内部)。
此外...它是匿名函数...意思是...你只能使用该函数一次(这就是为什么函数调用附加到函数声明的原因)。所以...
function regular()
{
function regular_closure()
{
}
(function () // this is anonymous
{
})(); // call the anonymous function.. which is also a closure
regular_closure(); // call the function
}
更多关于这个主题的内容:
当你执行
(function set() { /*code here*/ })();
它是一个接近等价于的标签
var set = function () { /*code here*/ };
set();
因此,当您调用Init()函数时,将会调用set函数。
set
变量(而且下面它甚至不是未定义的)。 - Zlatkoset
函数在外部函数作用域或 set
本身之外的任何地方都不可用。请查看此链接:https://gist.github.com/zladuric/dae9dc89297921f4f4023dee53e667fd或者我是否误解了您的意思? - Zlatko......与FunctionDeclaration不同,FunctionExpression中的标识符不能从中引用,也不会影响包围FunctionExpression的作用域。
- Dominique Fortin