简体   繁体   English

以下javascript代码结构是什么意思?

[英]What does following javascript code structure mean?

I have come across javascript code with following structure. 我遇到了以下结构的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

Questions are 问题是
1. What does this concept is called? 1.这个概念叫什么?
2. How do I call functions inside init function? 2.如何在init函数中调用函数?

UPDATE : Hope close voters understand an importance of this question. 更新 :希望close选民了解这个问题的重要性。

The variable somevar contains the responded object of a directly executed anonymous function, called IIFE . 可变somevar包含回应object一个直接执行匿名函数,称为IIFE The object has one property, init , what contains a anonymous function too. 该对象具有一个属性init ,该属性也包含一个匿名函数。

The functions inside the init function can only be used on the inside of the anonymous function ( scope ). init函数内部的函数只能在匿名函数( scope )的内部使用。

 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(); 

The structure you are referring to is known as the module pattern. 您所指的结构称为模块模式。

see module patterns in depth 深入了解模块模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM