JavaScript把區域性變數變成全域性變數的方法
阿新 • • 發佈:2021-05-08
首先我們要知道函式的自呼叫
函式的自呼叫—程式設計客棧—自呼叫函式
一次性的函式——宣告的同時,直接呼叫了
例如:
(function () { console.log("函式"); })();
我們會看到瀏覽器直接列印 函式
兩個字
頁面載入後.這個自呼叫函式的程式碼就執行完了
使用形式
(function (形參) { })(實參);
注意
自呼叫建構函式的方式,分號一定要加上
那麼如何把區域性變數變成全域性變數?
把區域性變數給window就可以了
(function (win) { var num=10;//區域性變數 //js是一門動態型別的語言,物件沒有屬性,點了就有了 win.num=num; })(window); console.log(num);
頁面打印出num了
應用案例1——將隨機數物件賦給window
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <script> //通過自呼叫函式產生一個隨機數物件,在自呼叫函式外面,呼叫該隨機數物件方法產生隨機數 (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> </head> <body> </body> </html>
應用案例2——產生隨機位置小方塊
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta > <title>title</title> <style程式設計客棧> .map{ width: 800px; height: 600px; background-color: #CCC; position: relative; } </style> </head> <body> <div class="map"></divCZKZM> <script src="common.js"></script> <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";//脫離文http://www.cppcns.com檔流 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); // function refresh(){ // window.location.reload(); // } // setTimeout(refresh(),1000); </script> </body> </html>
到此這篇關於javascript把區域性變數變成全域性變數的方法的文章就介紹到這了,更多相關javaScript 區域性變數變成全域性變數內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!