//函數的自調用 //一次性函數 (function (){ console.log("一次性"); })(); (function(win){ var num=20; win.num=num; })(window); //把局部變量給父類就能夠了 console.log(num);
//經過自調用函數產生一個隨機對象 (function(window){ //產生一個隨機 function Random(){ Random.prototype.getRandom=function(min,max){ return Math.floor(Math.random()*(max-min)+min); }; //把Random對象暴露給頂級對象window } window.Random=Random; })(window); var rm=new Random(); console.log(rm.getRandom(0,5));
<script> //產生隨機數對象的 (function (window) { function Random() { } Random.prototype.getRandom=function (min,max) { return Math.floor(Math.random()*(max-min)+min); }; //把局部對象暴露給window頂級對象,就成了全局的對象 window.Random=new Random(); })(window);//自調用構造函數的方式,分號必定要加上 //產生小方塊對象 (function (window) { //console.log(Random.getRandom(0,5)); //選擇器的方式來獲取元素對象 var map=document.querySelector(".map"); //食物的構造函數 function Food(width,height,color) { this.width=width||20;//默認的小方塊的寬 this.height=height||20;//默認的小方塊的高 //橫座標,縱座標 this.x=0;//橫座標隨機產生的 this.y=0;//縱座標隨機產生的 this.color=color;//小方塊的背景顏色 this.element=document.createElement("div");//小方塊的元素 } //初始化小方塊的顯示的效果及位置---顯示地圖上 Food.prototype.init=function (map) { //設置小方塊的樣式 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); }; //產生隨機位置 Food.prototype.render=function (map) { //隨機產生橫縱座標 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"; }; //實例化對象 var fd=new Food(20,20,"green"); fd.init(map); console.log(fd.x+"===="+fd.y); })(window); </script>