Home > Web Front-end > JS Tutorial > body text

Various ways to create namespaces in JavaScript

autoload
Release: 2021-04-02 09:45:46
Original
2078 people have browsed it

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; 
}());
Copy after login

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);  
   }
 };
Copy after login

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();
Copy after login

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);  
      }; 
 };
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!