如今经常听到模块化编程的这个概念,在WEB前端的领域更是如火如荼,相应的工具与框架层出不穷,那么到底为什么要模块化编程呢:
将一个复杂的程序依据一定的规则(规范)封装成几个块(文件),并进行组合在一起的编程方法;块的内部数据以及实现都是私有的,只是向外部暴露一些接口方法与外部其他模块通信
html代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<script src="module.js">script>
<script>
f1();
f2();
msg = 'newmsg';
f1();
f2();
script>
body>
html>
js代码
var msg = 'test';
function f1(){
console.log("f1()",msg);
}
function f2(){
console.log("f2()",msg);
}
html代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<script src="module.js">script>
<script>
obj.f1();
obj.f2();
obj.msg = 'new msg';
obj.f1();
obj.f2();
script>
body>
html>
js代码
var obj = {
msg:'zhouxingxing',
f1:function(){
console.log("f1()",this.msg);
},
f2: function(){
console.log("f2()",this.msg)
}
}
html代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.7.1/jquery.min.js">script>
<script src="module.js">script>
<script>
script>
body>
html>
js代码
(function(window){
var msg = 'test';
function f1() {
console.log("f1()", msg);
}
function f2() {
console.log("f2()", msg);
}
window.module3 = {f1,f2};
})(window);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<script src="module.js">script>
<script>
window.module3.f1();
window.module3.f2();
msg = "new msg";
window.module3.f1();
window.module3.f2();
script>
body>
html>
js代码
(function(window,$){
var msg = 'test';
function f1() {
console.log("f1()", msg);
}
function f2() {
console.log("f2()", msg);
}
$(window).css('background','red');
})(window, jquery);
<head>
<script src="1.js">script>
<script src="2.js">script>
<script src="3.js">script>
head>
//模块化之后的最大一个问题,增加了请求次数,本来只是请求1次,由于拆分成模块化,请求多次,如何避免这样的问题?
模块化的问题
1.请求过多
2.依赖模糊
3.难以维护
因为理想总是美好的,而现实总是残酷的,为了解决模块化的问题,提出了模块化的规范