Reputation: 125
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
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
Reputation: 1014
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. You should read a few articles about object oriented javascript and design patterns. Start with this one
Upvotes: 1