Home >Web Front-end >JS Tutorial >Various ways to create namespaces in JavaScript

Various ways to create namespaces in JavaScript

autoload
autoloadOriginal
2021-04-02 09:45:462182browse

Various ways to create namespaces in JavaScript

# In JavaScript global variables often cause Naming conflicts, and sometimes even rewriting variables are not in the order you imagined, so in order to avoid global variable name conflicts, creating a namespace becomes the optimal solution.

1. Implement through closure (Closure) and Object

Declare all variables and methods in the closure, and pass a

JSON Object Returns the public interface:

var NameSpace = NameSpace || {};
 NameSpace.Hello = (function() {   
 //待返回的公有对象  
  var self = {};   
  //私有变量或方法   
  var name = 'world';  
   //公有方法或变量   
   self.sayHello = function(_name) {    
    return 'Hello ' + (_name || name);  
     } ;   
     //返回的公有对象   
     return self; 
}());

2. Create Object through JSON object, the code is as follows:

var NameSpace = NameSpace || {}; 
NameSpace.Hello = {     name: 'world'   , sayHello: function(_name) {   
  return 'Hello ' + (_name || this.name);  
   }
 };

3. Create through function: (more complex)

This is a relatively common way of writing, by declaring a

function is implemented, set the initial variables in the function, and write the public method into prototype, such as:

var NameSpace = NameSpace || {}; 
/* Function */ 
NameSpace.Hello = function() {   
    this.name = 'world'; 
}; 
NameSpace.Hello.prototype.sayHello = function(_name) {   
    return 'Hello ' + (_name || this.name); 
}; 
var hello = new NameSpace.Hello(); 
hello.sayHello();

4. Create through function: (more Concise)

var NameSpace = NameSpace || {}; 
NameSpace.Hello = new function() {   
    var self = this;   
    var name = 'world';   
    self.sayHello = function(_name) {    
     return 'Hello ' + (_name || name);  
      }; 
 };

Recommended: "

2021 js interview questions and answers (large summary)"

The above is the detailed content of Various ways to create namespaces in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more