Search code examples
javascriptworkspace

need help understanding how to work with Name Space :(


I was searching over the Internet for good JS practices and found an interesting one (that sadly, I don't understand it entirely)

myNameSpace = function(){
  var current = null;
  function init(){...}
  function change(){...}
  function verify(){...}
  return{
    init:init,
    change:change
  }
}();
  • Where can I use this name space?
  • How can I use the names pace?
  • Is it really good idea to use this instead of Global?

Source of script: http://dev.opera.com/articles/view/javascript-best-practices/


Solution

  • You can also use a code like this, that lets you write OO JavaScript code. You should group only cohesive functions in one unit and build more objects like this as needed.

    Note that function buildFullName is a private function, since it can't be accessed from outside.

    I agree with you that is confusing, without previous JavaScript knowledge. The fact is that a function is a first class Object in JavaScript. You can nest functions within functions, they can have variables, and there are so many ways to combine them, there is no standard way like in Java. I think the article JavaScript Closure 101 can help you clear things up a bit.

    /** This is our Object definition and constructor */
    function Person(fname, lname) {
        this.firstName = fname;
        this.lastName = lname;
    }
    
    /** Anonymous function to avoid polluting the global namespace */
    (function () {
    
        /** This function will be defined public, we prefix the class name */
        function Person_toString() {
            //call buildFullName passing this, we could also call the function
            //as buildFullName(),  and it would work, but wouldn't have 'this'
            return buildFullName.call(this);
        }
    
        /** Another public function */
        function Person_buildGreeting() {
            return "Hi " + this.firstName;
        }
    
        /** This function is private! */
        function buildFullName() {
            return this.firstName + " " + this.lastName;
        }
    
        /** Here we augment the Object with public functions */
        Person.prototype = {
            toString: Person_toString,
            buildGreeting: Person_buildGreeting
        };
    
    })(); //execute the anonymous function immediately
    

    Example usage:

    var p1 = new Person('Jenny', 'Fairview');
    alert("toString()=" + p1.toString());
    alert("buildGreeting()=" + p1.buildGreeting());