下面的JavaScript代码结构是什么意思?
问题描述:
我遇到了以下结构的javascript代码。下面的JavaScript代码结构是什么意思?
var somevar = function(){
return {
init: function(){
function a(){} // no terminator in between functions.
function b(){}
function c(){} and so on
...
some jquery declarations
...
} // init ends
}; // return ends
}(); // somevar ends
问题是
1.这是什么概念被称为?
2.如何在init函数中调用函数?
UPDATE: 希望close
选民明白这个问题的重要性。
答
变量somevar
包含直接执行的匿名函数的响应object
,称为IIFE。该对象有一个属性,init
,也包含一个匿名函数。
init
函数内部的函数只能用于匿名函数的内部(范围)。
var somevar = function() {
return {
init: function() {
// 'a()' is only available inside of the 'init' function
function a() {
console.log("init");
}
a();
}
};
}(); // <-- here the outer function is executed directly
// the call of 'init'
somevar.init();
1 - JavaScript中,2 - 通过调用初始化 –
难道这仅调用一次性?如果我想分别调用函数c,我该怎么做? init返回什么? –
'init返回什么?' - 你没有显示它返回的结果 –