Namespaces

Javascript namespace

Javascript namespace


Global variables in JavaScript often cause naming conflicts, and sometimes even overriding variables is not in the order you expect, for example:

var sayHello = function() {
  return 'Hello var';
};

function sayHello(name) {
  return 'Hello function';
};

sayHello();

The final output is

Hello var

The best way to avoid global variable name collisions is to create namespaces.


Namespace role:

Manage variables to prevent global pollution, suitable for modular development.

1. Created by an object.

<script type="text/javascript">
        	
var test = {
		
	mike : {
			
	father : {},
			
	sister : {
        				
	name : 'cite',
        				
		},
			
 	},
 		
 	max : {
 			
 	father : {},
 			
	son : {
		
	lastName : 'bai',
		
	       }
	}
}
        	
</script>

For example, to call the name of the sister in mike in a test

console.log(test.mike.sister.name)

Simplify it like this

var name = test.mike.sister.name;
console.log(name);

But in this case, the meaning of creating a namespace is lost.

This method of using objects to implement namespaces is not commonly used .


2. Implemented through Closure and Object

<script type="text/javascript">
	
    var init = (function () {
    	
    	var name = '墨小白';
    	
    	function test() {
    		
    		console.log(name);
    		
    	}
    	
    	return function () {
    		
    		test();
    		
    	}//通过return保存到外部形成闭包.
    	
    }());
    
    init();//输出墨小白
    
</script>

this method

It is the most commonly used function to put the functions to be used in the global in a local area without polluting each other.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324848649&siteId=291194637