Possible Duplicate:
Javascript Namespacing
Im pretty new to JavaScript and was wondering if anyone could give me a good description of what is meant by JavaScript Namespacing?
Also any resources e.g. articles etc, are much appreciated on the subject.
Namespacing is the act of wrapping a set of entities, variables, functions, objects under a single umbrella term. JavaScript has various ways to do that, and seeing the examples will make the concept easier to understand.
JavaScript “namespace” is a programming paradigm that is utilized for assigning scope to the identifiers such as variables and function names. It is used to prevent collisions between the same-named variables and functions.
namespace property returns the custom namespace when the event was triggered. This property can be used by plugin authors to handle tasks differently depending on the namespace used. Tip: Namespaces beginning with an underscore are reserved for jQuery.
Namespaces in Python. A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves.
JavaScript is designed in such a way that it is very easy to create global variables that have the potential to interact in negative ways. 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:
var MyApplication = {
var1: someval,
var2: someval,
myFunc: function() {
// do stuff
}
};
Then instead of calling myFunc()
globally, it would always be called as:
MyApplication.myFunc();
Likewise, var1
always accessed as:
console.log(MyApplication.var1);
In this example, all of our application's code has been namespaced inside MyApplication
. It is therefore far less likely that our variables will collide with those created by other libraries or created by the DOM.
I use this namespacing technique, along with "use strict" outlined by Crockford
var MyNamespace = (function () {
"use strict";
function SomeOtherFunction() {
}
function Page_Load() {
}
return { //Expose
Page_Load: Page_Load,
SomeOtherFunction: SomeOtherFunction
};
} ());
MyNamespace.Page_Load();
Read up on a simple tutorial Here
Namespacing is used to avoid polluting the global namespace (no window. variables). In truth, each namespace is just a big variable, that has many properties and methods.
This happens, because in javascript you can have whole functions (methods) as variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With