js怎样理解面向对象

版权声明:Element https://blog.csdn.net/goucheng112/article/details/82596483

什么是对象

万物皆对象,对象有属性(高矮,胖瘦)和方法(他能做什么)。

什么是面向对象

我对面向对象的理解,面向对象最大的特点就是“使唤”。

什么是“使唤”,就是你有做的能力,我就让你去做。

我想吃饭,我就去找饭店,他能让我吃上饭。------饭店就是一个对象,他有让人吃饭的能力。

我想休息,我就找旅馆,他能让我住下来。--------旅馆是个对象,他有让人休息的能力。

面向对象就是,当我需要干什么事,就去找相应的对象,让他去做。我们负责使唤。

当我们没有这种相应功能的对象时,就只有面向过程去写这个对象,然后封装起来,通过留下的端口去调用他。

小例子:在平面中随机显示一个小方块。

思考:这里也有几个对象?他能做什么?

有两个对象,一个是负责显示的div,他起显示的作用。

一个是小方块,他会随机显示在平面中。

第一创建一个显示器对象起显示的作用,他有宽高和背景颜色的基本属性,

第二部创建一个小方块的对象,他除了宽高和背景颜色外,他还有个随机显示的行为。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .map {
            width: 800px;
            height: 600px;
            background-color: gray;
            position: relative;

        }
    </style>
</head>

<body>
    //创建背景div对象
    <div class="map"></div>
    <script>
        // 封装一个产生随机数的函数,使用立即函数。
        (function (window) {
            function Random() {};
            Random.prototype.getRandom = function (min, max) {
                return Math.floor(Math.random() * (max - min) + min)
            };
            window.Random = new Random();
        })(window);


        //创建小方块对象

        (function (window) {
            //找到地图
            var map = document.querySelector(".map");
            //方块的基本属性创建
            function Food(width, height, color) {
                //宽高的设置
                this.height = height || 20;
                this.width = width || 20;
                this.color = color || "red";
                //位置的设置
                this.x = 0;
                this.y = 0;
                //小方块的标签创建
                this.element = document.createElement("div");
            };
            Food.prototype = {
                //方块在显示器中随机显示的行为放到原型中封装。
                init: function () {
                    //随机产生横纵坐标
                    var x = Random.getRandom(0, map.offsetWidth / this.width) * this.width;
                    var y = Random.getRandom(0, map.offsetHeight / this.height) * this.height;
                    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;
                    
                    this.x = x;
                    this.y = y;
                    var div = this.element;
                    div.style.left = this.x + "px";
                    div.style.top = this.y + "px";
                    //把方块加到map上
                    map.appendChild(div);
                }
            }
            var food = new Food();
            food.init()
            })(window)
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/goucheng112/article/details/82596483
今日推荐