开发者

Private functions in JavaScript

开发者 https://www.devze.com 2023-01-25 18:19 出处:网络
In a jQuery-based web application I have various script where multiple files might be included and I\'m only using one of them at a time (I know not including all of them would be better, but I\'m jus

In a jQuery-based web application I have various script where multiple files might be included and I'm only using one of them at a time (I know not including all of them would be better, but I'm just responsible for the JS so that's not my decision). So I'm wrapping each file in an initModule() function which registers various events and does some initialization etc.

Now I'm curious if there are any differences between the following two ways of defining functions not cluttering the global namespace:

function initStuff(someArg) {
    va开发者_Go百科r 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 */
}


The major difference between these two approaches resides in the fact WHEN the function becomes available. In the first case the function becomes available after the declaration but in the second case it's available throughout the scope (it's called hoisting).

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're basically the same.


this is a model that helped me to manage 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

精彩评论

暂无评论...
验证码 换一张
取 消