user906080
user906080

Reputation: 125

Javascript pattern setup difference

I am working on a small one-page scrolling site with the use of jQuery. Being new to javascript, I've come across many different ways other developers organize their code. With a simple site with small javascript interaction, I'm wondering what the difference is between the following snippets of code that I've seen on other sites.

First

var NS = NS || NS
NS = {
    init: function() {},
    buildNav: function() {},
    scrollToSection: function() {}
}

$( document ).ready( NS.init() );

Second

var NS = NS || NS;
NS = new (function() {
    var name = 'Basic';
    var self = this;
    self.getName = function() { return name; };
});
NS.Home = new (function() {
    // variables..are these private or public
    var self = this;
    self.init = function() {
      // initiate
    }

    self.scrollToSection = function() {
      // scroll section
    }

    // public or private method?
    function buildNav() {
    }
});

$(document).ready(function() { NS.Home.init(); });

Third

var NS = NS || NS;

NS.Home = new function() {
  var foo = $('#htmlelement');

  this.scrollToSection() {
    // scroll section
  };
  this.init = function() {
    buildNav();
  };

  function buildNav() { }
}
$( document ).ready( NS.Home.init() );

Forth

(function($){
    $.fn.homepage = function() { 
        function buildNav() { }
        function init () { } 
    };
    $.fn.otherpage = function() {
        function doSomething() { }
        function init () { }
     }
})(jQuery);

$(document).ready(function () {
    $('#homepage-element').homepage();
}

Upvotes: 1

Views: 216

Answers (2)

Darren Lewis
Darren Lewis

Reputation: 8488

Take a look at the content presented here by Elijah Manor. Some really good presentations and content on javascript best practices.

Upvotes: 0

saarthak
saarthak

Reputation: 1014

  1. var NS = NS || NS; This line initialises NS to a default value if the passed value is null or undefined. All the three create a singleton object of NS - which acts like a namespace.
  2. First, Second and Third explain different styles of object oriented programming practices.
  3. In First, the NS object is created via object literal notation and therefore all its functions are public, and variable that you will be creating for NS will also be public.
  4. Second and Third are quite similar, except Second is more messy and Third is more crisp. Second and Third both declare some exposed methods on the NS object (created via anonymous constructor) and some private functions.
  5. Second and Third declare an property dynamically by the use of anonymous constructor function.

You should read a few articles about object oriented javascript and design patterns. Start with this one

Upvotes: 1

Related Questions