自調(diào)用函數(shù)的兩種形式:
//第一種自調(diào)用方式
(function(形參){
var num =10; //局部變量,外部訪問不到
})(實(shí)參);
//第二種自調(diào)用方式
(function(形參){
var num =10; //局部變量,外部訪問不到
}(實(shí)參));
自調(diào)用函數(shù)在頁面加載完成后數(shù)據(jù)庫中局部變量必須,代碼也就執(zhí)行完了。
局部變量變成全局變量如何把局部變量變成全局變量呢,把局部變量給就行了。
(function(){
var num=10; //局部變量
//JS是一個(gè)動(dòng)態(tài)類型語言,對(duì)象沒有屬性,點(diǎn)了就有了
window.num=num; //把局部變量暴露給window
})();
console.log(num);
案例:通過自調(diào)用函數(shù),產(chǎn)生一個(gè)隨機(jī)數(shù)對(duì)象數(shù)據(jù)庫中局部變量必須,在自調(diào)用函數(shù)外面,調(diào)用該隨機(jī)數(shù)對(duì)象方法產(chǎn)生隨機(jī)數(shù)。
(function(){
//產(chǎn)生隨機(jī)數(shù)的構(gòu)造函數(shù)
function Random(){
}
//在原型對(duì)象中添加方法
Random.prototype.getRandom = function(min,max){
return Math.floor(Math.random()*(max-min)+min);
};
//把Random對(duì)象暴露給定頂級(jí)對(duì)象window,這樣外部就可以直接使用這個(gè)對(duì)象。
window.Random = Random;
})();
var rm = new Random();
console.log(rm.getRandom(10,40));
案例:隨機(jī)產(chǎn)生小方塊
Title
<script>
//產(chǎn)生隨機(jī)數(shù)對(duì)象的
(function(window){
function Random(){}
Random.prototype.getRandom=function(min,max){
return Math.floor(Math.random()*(max-min)+min);
};
//把局部對(duì)象暴露給window頂級(jí)對(duì)象,就成了全局對(duì)象
window.Random = new Random();
})(window);//自調(diào)用構(gòu)造函數(shù)的方式,一定要加分號(hào)
//產(chǎn)生小方塊對(duì)象
(function(){
//食物的構(gòu)造函數(shù)
function Food(width,height,color){
this.width=width||20;//默認(rèn)的小方塊的寬
this.height=height||20;//默認(rèn)的小方塊的高
//橫坐標(biāo)‘縱坐標(biāo)
this.x=0;//橫坐標(biāo)隨機(jī)產(chǎn)生
this.y=0;//縱坐標(biāo)隨機(jī)產(chǎn)生
this.color=color;//小方塊的背景顏色
this.element=document.createElement("div");//小方塊元素
}
// 初始化小方塊顯示的效果和位置——————顯示地圖上
Food.prototype.init = function(map){
//設(shè)置小方塊的樣式
var div = this.element;
div.style.position = "absolute";
div.style.width = this.width+"px";
div.style.height = this.height+"px";
div.style.backgroundColor = this.color;
//把小方塊加到map地圖中
map.appendChild(div);
this.render(map);
};
//產(chǎn)生隨機(jī)位置
Food.prototype.render = function(map){
//隨機(jī)產(chǎn)生橫縱坐標(biāo)
var x=Random.getRandom(0,map.offsetWidth/this.width)*this.width;
var y=Random.getRandom(0,map.offsetHeight/this.height)*this.height;
this.x=x;
this.y=y;
var div = this.element;
div.style.left=this.x+"px";
div.style.top=this.y+"px";
};
//把局部對(duì)象暴露給window頂級(jí)對(duì)象,就成了全局對(duì)象
window.Food = Food;
})();
var map = document.querySelector(".map");
var food = new Food(20,20,"green");
food.init(map);
</script>