This usually comes down to encapsulating your objects in a "namespace". I use quotes there because the term is not official semantics in JavaScript, but rather what is achieved by encapsulating the underlying object.
There are several ways to do this, and it ultimately comes down to personal preference.
One approach is to simply use the underlying JS object and store everything in it. The name of the object should be semantic and give the object some meaning, but otherwise its purpose is simply to wrap your own code and not allow it from the global namespace.
var SomeName = {
alpha: 1,
beta: {a: 1, b: 2},
gamma: function(){
SomeName.alpha += 1;
}
}
. , , , 'this' - . SomeName.gamma SomeName.alpha .
- . 'private' . .
var SomeName = (function(){
var self = this;
var privateVar = 1;
var privateFunc = function() { };
this.publicVar = 2;
this.publicFunc = function(){
console.log(privateVar);
console.log(this.publicVar);
setTimeout(function(){
console.log(self.publicVar);
console.log(privateVar);
}, 1000);
};
}();
- , . , jQuery, , $, , jQuery $ :
var SomeName = (function($){
console.log($('div'));
})(jQuery);