The practice of namespacing is usually to create an object literal encapsulating your own functions and variables, so as not to collide with those created by other libraries.
Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions.
In practice this means you should avoid creating global objects unless they are absolutely necessary.
Let's explain It better with my favourite pattern, Module Pattern:
(function () {
// code
})();
In this way we create a function that It calls itself immediately. These are also known as IIFE
After creating new scope, we need to namespace our code so that we can access any methods we return.
var Module = (function () {
// code
})();
So if we want to define a private method we should do something like this:
var Module = (function () {
var privateMethod = function () {
// do something
};
})();
Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions.
In practice this means you should avoid creating global objects unless they are absolutely necessary.
Let's explain It better with my favourite pattern, Module Pattern:
(function () {
// code
})();
In this way we create a function that It calls itself immediately. These are also known as IIFE
After creating new scope, we need to namespace our code so that we can access any methods we return.
var Module = (function () {
// code
})();
So if we want to define a private method we should do something like this:
var Module = (function () {
var privateMethod = function () {
// do something
};
})();
Σχόλια
Δημοσίευση σχολίου