This particular pattern when seen at the top of files is used to create a namespace, i.e. a named object under which functions and variables can be created without unduly polluting the global object.
1 Preventing override:
Imagine you have your code split over multiple files and your co-workers are also working on an Object called Base
. Then it could lead to the case that someone already defined Base
and assigned functionality to it (like a pizza
function). Then you would override it, if you were not checking if it already exists.
// Definition of co-worker "A" in "A.js"
var Base = {};
Base.pizza = function() {
alert('I like pizza!');
};
// Definition of co-worker "B" in "B.js"
var Base = {};
Base.donut = function() {
alert('I like donuts!');
};
In this case the pizza
function will be gone if you load the JavaScript file B.js
after A.js
in your HTML because B
defines a new Base
object (and thus overrides the existing one from A
) so it only knows about the donut
function.
So you need to use var Base = Base || {};
which means "Base
will be assigned to Base
(if it exists already) or a new blank object (if Base
does not exist already).
Solution
var Base = Base || {};
// Definition of co-worker A in A.js
Base.pizza = function() {
alert('I like pizza!');
};
// Definition of co-worker B in B.js
var Base = Base || {};
Base.donut = function() {
alert('I like donuts!');
};
Because A and B are now checking for the existence of Base before they define their methods, you can load A.js
and B.js
in any order without overriding each other's methods (if they have different names). So you will always get a Base
object which has the methods pizza
and donut
(Cheers!).
2 Defining a new object
If you've read through the first example then you already now what's the purpose of the || {}
.
Because if there is no existing Base
object then the OR-case will become active and creates a new object, so you can assign functions to it. Like:
var Base = {};
Base.pizza = function() {
alert('I like pizza!');
};
Hope it Helps!