Recommend way of scoping private members in javascript module

Conside the following JavaScript code. The function definitions all seem to achieve the same thing. Is there any recommended convention for defining the functions which are then 'revealed' in the return dictionary object?

var testModule = (function(){
      var counter = 0;

      var localFunc1 = function() {
        return "local 1";
      }

      function localFunc2() {
        return "local 2";
      }

      this.localFunc3 = function() {
        return "local 3";
      }

      localFunc4 = function() {
        return "local 4";
      }

      return {      
        proxy1: localFunc1,
        proxy2: localFunc2,
        proxy3: localFunc3,
        proxy4: localFunc4
      };
    })();

Answers


I don't think that there is any real preferred method. The most common setup I've seen involves creating all of your methods as local (using var) then returning an object that exposes the public methods.

A couple of things to note:

  • this.localFunc3 will only work if your object is instantiated with the 'new' keyword
  • when returning your object, remove the () from each function so that you are returning a reference to the function and not the function's returned value
  • localFunc4 will be global since it has no 'var' keyword in front of it

When working with a module pattern like this, I tend to go for something along the lines of:

var Obj = ( function () {
    var private_static = 'this value is static';
    return function () {
        //-- create return object
        var _self = {};
        //-- create private variables
        var private_variable = 'this value is private';
        var func1 = function () {
            return 'value 1';
        };
        //-- attach public methods
        _self.func1 = func1;
        //-- return the object
        return _self;
    };
} )();

Some notes about this method:

  • allows for private static variables (if you don't need private static variables, you can remove the closure)
  • by creating the _self reference first, you can pass a self reference to any objects instantiated from within that need a reference to their parent
  • I like that I can reference all internal functions without _self.whatever or this.whatever, ignoring whether or not they are private or public

Need Your Help

php css how to change name color based on membership?

php html css colors

i want to create member badges on evolutionscript forum

python for loop expression of iterator

python for-loop list-comprehension

I have a for loop in which I use the iterator always in the same manner, like this

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.