Home  >  Article  >  Web Front-end  >  How to modularize programming in Javascript

How to modularize programming in Javascript

一个新手
一个新手Original
2017-09-19 10:13:541552browse

Modular programming can make the business logic clearer. Unlike other traditional programming languages, Javascript does not provide a native and organized way to introduce modules. Here we mainly discuss: Object-based Javascript modular programming. That is, javascript modularization (package.class.method).

Traditional writing method:

Mix different functions together in a Javascript file, such as:

function m1(arg1, arg2){
	//…
}
function m2(){
	//…
}

This method "pollutes" Global variables are not included, and there is no guarantee that conflicts will not occur. The most important thing is that the relationship between modules and members is not obvious.

How to write objects:

Write different modules into different objects, and place all module members in the object.

var module1 = new Object({
	_appId : 0,
	URL:{
		process1:function(){
			return ‘/data/process1’;
		},
		process2:function(){
			return ‘/data/process2’;
		}
},
	m1: function(){
		//…
},
m2:function(params){
	var appId = params[‘appId’];
	var package = params[‘package’];
	//…
},
m3:{
	init:function(){
		//initial something
	},
	process:function(appId, package){
		//
	}
}
});

Analysis:

The following writing method:

var module1 = new Object({
	//…
})

can be abbreviated as:

var module1 = {
	//…
}

Constant related settings :

_appId: 0,

You can set certain constant values. This constant can also be used to pass the value of el expression. In the jsp file, add

<script type=”text/javascript”>
	module1._appId = ${appId}; //这样可以将服务端的appId的值设置到js中
</script>

Note:

EL expression ${appId} can only be used in jsp files, cannot be used in js files.

Another way to set a constant group is:

URL:{
		process1:function(){
			return ‘/data/process1’;
		},
		process2:function(){
			return ‘/data/process2’;
		}
},

There are two ways to pass variables in functions:

1) The simpler one is:

process:function(appId, package)

Here appId and package are the single-layer values ​​passed.

2) Array transfer:

m2:function(params){
	var appId = params[‘appId’];
	var package = params[‘package’];
	//…
},

The format when called is as follows:

module1.m2({appId:10, package:’hello’})

Multi-layer object encapsulation:

m3:{
	init:function(){
		//initial something
	},
	process:function(appId, package){
		//
	}
}

The above is the detailed content of How to modularize programming 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