如何把局部变量变成全局变量

自调用函数的两种形式:

    //第一种自调用方式
    (function(形参){
        var num =10;  //局部变量,外部访问不到
    })(实参);

    //第二种自调用方式
    (function(形参){
        var num =10;  //局部变量,外部访问不到
    }(实参));
自调用函数在页面加载完成后,代码也就执行完了。

局部变量变成全局变量

如何把局部变量变成全局变量呢,把局部变量给window就行了。
    (function(){
        var num=10;  //局部变量
        //JS是一个动态类型语言,对象没有属性,点了就有了
        window.num=num;  //把局部变量暴露给window
    })();
    console.log(num);

案例:通过自调用函数,产生一个随机数对象,在自调用函数外面,调用该随机数对象方法产生随机数。

    (function(){
        //产生随机数的构造函数
        function Random(){

        }
        //在原型对象中添加方法
        Random.prototype.getRandom = function(min,max){
            return Math.floor(Math.random()*(max-min)+min);
        };

        //把Random对象暴露给定顶级对象window,这样外部就可以直接使用这个对象。
        window.Random = Random;
    })();

     var rm = new Random();
     console.log(rm.getRandom(10,40));

案例:随机产生小方块

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .map{
            width: 800px;
            height: 800px;
            background-color: #ccc;
            position: relative;
        }
    </style>
</head>
<body>
<div class="map"></div>
<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(){
            //食物的构造函数
        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";
        };
        //把局部对象暴露给window顶级对象,就成了全局对象
        window.Food = Food;
    })();
    var map = document.querySelector(".map");
    var food = new Food(20,20,"green");
    food.init(map);
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/sleepwalker_1992/article/details/80930255
今日推荐