In the past it was very common to see global variables in snippets of JavaScript code across the web, such as:
name = "Spock"; function greeting() { return "Hello " + name; }
The simplest method of creating a namespace is to use an object literal.
var foo = {}; foo.name = "Spock"; foo.greeting = function() { return "Hello " + foo.name; }
var foo = { name: "Spock", greeting: function() { return "Hello " + foo.name; } };
Another problem with this approach is that greeting needs to refer to ‘foo.name’ rather than just ‘name’.
Another method of creating a namespace is through the use of a self executing function.
var foo = (function(){ // Create a private variable var name = "Spock"; // Create a private function var greeting = function() { return "Hello " + name; }; // Return an object that exposes our greeting function publicly return { greeting: greeting }; })();
console.log(foo.greeting() === "Hello Spock"); // true
Taken from Kevan Stannard post on the same.
9:12 PM |
Category: |
0
comments
Comments (0)