Private functions in JavaScript

In a jQuery web application, I have various scripts where several files can be included, and I use only one of them at a time (I know that not including all of them would be better, but I'm just responsible for JS, not my decision). So I wrap each file in an init Module () function that logs various events and does some initialization, etc.

Now I'm curious if there are differences between the two ways of defining functions that do not clutter the global namespace:

 function initStuff(someArg) { var someVar = 123; var anotherVar = 456; var somePrivateFunc = function() { /* ... */ } var anotherPrivateFunc = function() { /* ... */ } /* do some stuff here */ } 

and

 function initStuff(someArg) { var someVar = 123; var anotherVar = 456; function somePrivateFunc() { /* ... */ } function anotherPrivateFunc() { /* ... */ } /* do some stuff here */ } 
+6
javascript scope
source share
2 answers

The main difference between the two approaches is when the function becomes available. In the first case, the function becomes available after the announcement, but in the second case, it is available throughout the area (it is called lifting).

 function init(){ typeof privateFunc == "undefined"; var privateFunc = function(){} typeof privateFunc == "function"; } function init(){ typeof privateFunc == "function"; function privateFunc(){} typeof privateFunc == "function"; } 

other than that, they are basically the same.

+8
source share

this is the model that helped me manage the modules in javascript:

base.js:

 var mod = {}; mod.functions = (function(){ var self = this; self.helper1 = function() { } ; self.helper2 = function() { } ; return self; }).call({}); 

module_one.js

 mod.module_one = (function(){ var //These variables keep the environment if you need to call another function self = this, //public (return) priv = {}; //private function priv.funA = function(){ } self.somePrivateFunc = function(){ priv.funA(); }; self.anotherPrivateFunc = function(){ }; // ini module self.ini = function(){ self.somePrivateFunc(); self.anotherPrivateFunc(); }; // ini/end DOM $(function() { }); return self; // this is only if you need to call the module from the outside // exmple: mod.module_one.somePrivateFunc(), or mod.module_one.ini() }).call({}); 
0
source share

All Articles