打仗最好的方法是实践,做生意最好的方法是实践,学习最好的方法是实践。
勇于实践,哪管春夏与秋冬。下来就来用案例实践。
一、html文件
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="require.js"></script>
<script type="text/javascript">
require.config({
baseUrl: "js/",
paths: {
"jquery": ["jquery-1.8.3.min"],
"test": ["test"]
}
});
require(["jquery","test"], function($,t){
t.hellob();
});
</script>
</head>
<body>
<span>body</span>
</body>
</html>
二、新建无依赖模块
define(function(){
var i = {
int : function (){
this.helloc();
},
hellob : function(){
alert("b");
},
helloc : function(){
alert("c");
}
};
var q = {
hellod:function () {
alert("d");
}
};
return i.int(),q.hellod(),i
});
三、依次输出的顺序是:C、D、B
四、测试cookie,localStorage,依赖模块,形参冲突
html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="require.js"></script>
<script type="text/javascript">
require.config({
baseUrl: "js/",
paths: {
"jquery": ["jquery-1.8.3.min"],
"test": ["test"],
"cookies": ["cookies.min"]
}
});
require(["jquery","testc"], function($,t){
t.hellob();
//t.int("hello world"); 此处可调用testc.js的初始化程序
});
</script>
</head>
<body>
<span>body</span>
</body>
</html>
testc.js
define(["cookies"], function(c){
var i = {
int : function (c){
this.helloc(c);
c.set("xixi2","mimi"); //执行的过程中此处会报错,因为c会被认为是函数传过来的参数,而不是cookies传过来的c。所以要注意requirejs的参数与自定义函数参数的命名冲突问题。
window.localStorage.setItem("gaga",3);
console.log("xiaoshuang");
},
hellob : function(){
alert("b");
},
helloc : function(e){
alert(e);
}
};
var q = {
hellod:function () {
alert("d");
}
};
return i.int("guagua"),q.hellod(),i
});