侧边栏

前端学习:JS(面向对象)代码笔记

前端学习:JS(面向对象)代码笔记

前端学习:JS面向对象知识学习(图解)

创建类和对象

创建对象方式1调用Object函数

<body>
</body>
<script type="text/javascript">

        //新建英雄:刘备
        var hero=new Object();
        hero.name='刘备';
        hero.blood=100;
        hero.weapon='双股剑';
        hero.attack=function(){
            return this.name+'使用'+this.weapon+'发起了攻击';
        };
        
        alert(hero.attack());
        
        
        var hero2=new Object();
        hero2.name='关羽';
        hero2.blood=100;
        hero2.weapon='青龙偃月刀';
        hero2.attack=function(){
            return this.name+'使用'+this.weapon+'发起了攻击';
        };
        
        alert(hero2.attack());
        
</script>
View Code

创建对象方式2使用字面形式

<body>
</body>
<script type="text/javascript">

         var stu1={
              name:'张三',
              age:28,
              sex:'',
              show: function(){
                  return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
              }
         };
         
         alert( stu1.show()  );
         
         var stu2={
                 name:'李四',
                 age:18,
                 sex:'',
                 show: function(){
                     return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
                 }
         };
            
         alert( stu2.show()  );
        
</script>
View Code

创建对象方式3使用工厂函数创建多个对象

<body>
</body>
<script type="text/javascript">

         //形参
         var createPerson=function(name,age,sex){
                 var person = new Object();
                 person.name=name;
                 person.age=age;
                 person.sex=sex;
                 person.show=function(){
                     return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
                 }
                 return person;
         };
         
         
         var p1=createPerson('张三',18,'');
         var p2=createPerson('李四',19,'');
         var p3=createPerson('王五',20,'');
         
         alert(p1.show());
         alert(p2.show());
         alert(p3.show());


</script>
View Code

创建对象方式4调用构造函数创建对象

<body>
</body>
<script type="text/javascript">

        //定义一个Person类
        function Person(name,age,sex){
             //this代表的是当前对象
             
             //当前对象的名字=需要设置的名字
             this.name=name;
             this.age=age;
             this.sex=sex;
             
             this.show=function(){
                 return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
             }
             
        }

        //创建三个对象
        var p1=new Person('张三',27,'');
        var p2=new Person('李四',28,'');
        var p3=new Person('王五',29,'');
        
        
        alert(p1.show());
        alert(p2.show());
        alert(p3.show());
        
        console.log(p1.show===p2.show);
        console.log(p1.show===p3.show);
         

</script>
View Code

静态成员和实例成员

静态成员和实例成员

<body>
</body>
<script type="text/javascript">

        //静态成员    类名.成员名  
        /*
        var MyMath={
             PI:3.1415,
             MAX:function(){
                 return 9999;
             },
             MIN:function(){
                 return 1;
             }
        };
        
        
        console.log(MyMath.PI);
        console.log(MyMath.MAX());
        console.log(MyMath.MIN());
        */                
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
        //实例成员   对象名.成员名 
        function Student(name,age,sex){
            
            this.name=name;
            this.age=age;
            this.sex=sex;
            
            this.show=function(){
                return 'name='+name+'\nage='+age+'\nsex='+sex;
            }
        }
        
        //通过Student类的构造函数创建一个具体的实例对象
        var stu1=new Student('小红帽',18,'');
        var stu2=new Student('大灰狼',28,'');
        
        
        console.log('姓名:'+stu1.name );
        console.log('姓名:'+stu2.show()  );     
        
</script>
View Code

原型

使用全局函数

<body>
  
</body>
<script type="text/javascript">

            function Student(name,age,sex){
                
                this.name=name;
                this.age=age;
                this.sex=sex;
                this.show=show;
                
            }
            //全局函数
            var show=function(){
                return 'name='+name+'\nage='+age+'\nsex='+sex;
            };
            
            var stu1=new Student("DICK",22,"");
            var stu2=new Student("DICK",22,"");
            
            //比较的是这两个对象中show方法保存的内存地址
            console.log(stu1.show===stu2.show);      //true

</script>
View Code

使用构造函数的原型解决方法的重复创建问题

<body>
  
</body>
<script type="text/javascript">

            //得到一个结论:以后我们在定义一个类的函数的时候,不要定义在该类的构造函数中,应该
            //定在该类的构造函数的原型中,这样更加高效一些.
         

            //Student类的构造函数
            function Student(name,age,sex){
                
                this.name=name;
                this.age=age;
                this.sex=sex;
                
            }
            
            //向Student类的构造函数的原型中插入show方法
            Student.prototype.show=function(){
                return '在原型中生成的:   name='+this.name+'\nage='+this.age+'\nsex='+this.sex;
            };
    
            
            var stu1=new Student("DICK",22,"");
            var stu2=new Student("KING",22,"");
            
            console.log(stu1.show());
            console.log(stu2.show());
            
            //比较的是这两个对象中show方法保存的内存地址
            console.log(stu1.show===stu2.show);      //true
            

</script>
View Code

对象的原型

<body>
</body>
<script type="text/javascript">

            //Student类的构造函数
            function Student(name,age,sex){
                
                this.name=name;
                this.age=age;
                this.sex=sex;
                this.eat=function(){
                    console.log('我在构造函数中吃东西');
                }            
                
            }
            
            Student.prototype.eat=function(){
                console.log('我在构造函数的原型中吃东西');
            }    
            
            //构造方法的原型      Student.prototype 
            //对象的原型          对象名.__proto__
            var stu=new Student("KING",22,"");
            
            //我们发现构造方法的原型和对象的原型指向的是同一个地址 
            //console.log(stu.__proto__===Student.prototype);
            
            
            
            //当构造函数中和构造函数的原型中同时定义了同一个方法,这个时候会调用构造函数中的eat方法.
            stu.eat();
            
</script>
View Code

属性的查找规则

<body>
</body>
<script type="text/javascript">
        //Student类的构造函数
        function Student(name,age,sex){
            
            this.name=name;
            this.age=age;
            this.sex=sex;
            
        }
        
        //在Student类的构造函数的原型中存入属性
        Student.prototype.txt='xxx';
        
        var stu1=new Student("KING",22,"");
        //该段代码并没有修改掉原型中txt的值,是在在stu1对象中新建了一个txt属性=abc
        //stu1.txt='abc';
        Student.prototype.txt='ABC';
        var stu2=new Student("KING",22,"");
        
        console.log('stu1='+stu1.txt);    //abc
        console.log('stu2='+stu2.txt);    //xxx    
        
</script>
View Code

在原型中写入多个方法属性-精简写法

<body>
</body>
<script type="text/javascript">

     /*
     function Person(){
         
     }
     Person.prototype.eat=function(){
         console.log('eat');
     }
     
     Person.prototype.run=function(){
         console.log('run');
     }
     
     Person.prototype.sleep=function(){
         console.log('sleep');
     }
     
     Person.prototype.from='地球 ';
     
     var p1=new Person();
     p1.eat();
     p1.run();
     p1.sleep();
     */

     function Person(){
         
     }
     Person.prototype={
            from: '地球',
            eat: function(){
                 console.log('eat');
            },
            run: function(){
                    console.log('run');
               },
               sleep: function(){
                 console.log('sleep');
            }
     };
     
     var p1=new Person();
     p1.eat();
     p1.run();
     p1.sleep();
     alert(p1.from);
 
</script>
View Code

原生对象的原型

<body>
</body>
<script type="text/javascript">
        //Array类的对象
        var arr=[];  
        
        console.log(Array.prototype===Array.prototype);   //true
        //          对象的原型      构造函数的原型    
        console.log(arr.__proto__===Array.prototype);     //true
        
        console.log(Object.prototype===Array.prototype);  //false   
        
</script>
View Code

拓展原生对象中原型的方法

<body>
</body>
<script type="text/javascript">
        var arr=[21,22,43,67,12,34,20,10];
        console.log('排序前:  '+arr);
        arr.sort();
        console.log('排序后:  '+arr);
        
        //求出数组中所有的偶数的和
        //拓展Array类构造函数的原型中的方法: getSum()
        
        Array.prototype.getSum=function(){
            var sum=0;   
            for(var i=0;i<this.length;i++){
                if(this[i]%2==0){
                    sum+=this[i];
                }
            }
            return sum;
        }
        
        //错误的写法!!!!!!
        /*
        Array.prototype={
              getSum:function(){
                  var sum=0;   
                for(var i=0;i<this.length;i++){
                    if(this[i]%2==0){
                        sum+=this[i];
                    }
                }
                return sum;
              }
        };
        */        
        
        console.log(arr.getSum());
        
</script>
View Code

案例:随机生成方块

 案例前的练习

Demo01(JS插入与使用)

<body>

</body>
<script type="text/javascript" src="index1.js"></script>
<script type="text/javascript" src="index2.js"></script>
<script type="text/javascript" src="index3.js"></script>
<script type="text/javascript">

       console.log(num1);
       console.log(num2);
       console.log(num3);
       fn1();
       fn2();
       fn3();
</script>
View Code

index1.js

var num1=111;

function fn1(){
    alert('执行了fn1方法');
};
View Code

index2.js

var num2=222;

function fn2(){
    alert('执行了fn2方法');
};
View Code

index3.js

var num3=333;

function fn3(){
    alert('执行了fn3方法');
};
View Code

index(自调用函数)

<body>
</body>

<script type="text/javascript" src="student.js"></script>
<script type="text/javascript" src="superuser.js"></script>


<script type="text/javascript">

        var stu={
            name:'张三',
            age:20,
            sex:'男孩子'
        };
            
            
        var stu1=new Student(stu);
        alert(stu1.show());


        
        
        
</script>
View Code

student.js

//自调用函数
(function(){
    /*
    function Student(name,age,sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
    };
    */
    
    
    function Student(options){
        options=options||{};
        this.name=options.name||'学生';
        this.age=options.age||18;
        this.sex=options.sex||'女';
        
        
    };
    
    Student.prototype.show=function(){
        return "name="+this.name+"\tage="+this.age+"\tsex="+this.sex;
    };

    
    //向外界暴露Student类的构造函数
    window.Student=Student;
    

})();
View Code

superuser.js

(function(){
    
    //超级管理员
    function SuperUser(name,age,sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
    };

    SuperUser.prototype.show=function(){
        return "name="+this.name+"\tage="+this.age+"\tsex="+this.sex;
    };
View Code

随机生成方块

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
       div{
           height: 600px;
           width:600px;
           background-color: #C0C0C0;
       }
</style>
</head>

<body>
    <div id="container">
    </div>
</body>

<script type="text/javascript" src="tools.js"></script>
<script type="text/javascript" src="box.js"></script>
<script type="text/javascript" src="main.js"></script>

</html>
View Code

box.js

//自调用函数
(function(){
    
    //新建一个Box类
    function Box(map,options){
        options=options||{};
        this.height=options.height||20;
        this.width=options.width||20;
        this.x=options.x||0;
        this.y=options.y||0;
        this.backgroundColor=options.backgroundColor||'red';
        
        
        
        //新建一个div标签
        this.div=document.createElement('div');
        map.appendChild(this.div);
        this.map=map;
        
        //新建div的标签并且设置样式
        this.init();
    
    };
    

    Box.prototype.init=function(){
        
        var div=this.div;
        //设置div的样式
        div.style.backgroundColor=this.backgroundColor;
        div.style.height=this.height+'px';
        div.style.width=this.width+'px';
        div.style.x=this.x+'px';
        div.style.y=this.y+'px';
        //让我们新建的格子脱离文档流
        div.style.position='absolute';
        
        
        //随机生成小格子的X轴和Y轴的坐标
        this.Random();
        
        
        
    };
    
    
    Box.prototype.Random=function(){
        
    this.div.style.left=Tools.getRandom(1,this.map.offsetWidth/this.width-1)*this.width+'px';
        this.div.style.top=Tools.getRandom(1,this.map.offsetHeight/this.height-1)*this.height+'px';
        var r=Tools.getRandom(0,255);
        var g=Tools.getRandom(0,255);
        var b=Tools.getRandom(0,255);
        this.div.style.backgroundColor='rgb('+r+','+g+','+b+')';
        
        
    }
    

    //对外暴露Box的构造函数
    window.Box=Box;

    
})();
View Code

main.js

(function(){
    
    
    var elements=[];
    var container=document.getElementById('container');
    for(var i=0;i<10;i++){
        var box=new Box(container);
        elements.push(box);
    }
    setInterval(function(){
        
        for(var i=0;i<elements.length;i++){
            elements[i].Random();
        }
    },1000);
    
    
})();
View Code

tools.js

var Tools={
    //随机生成[0,600]之间随机数整数
    getRandom:function(min,max){
          min = Math.ceil(min);
          max = Math.floor(max);
          return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 
    }        
        
};
View Code

案例:贪吃蛇

更新中。。。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>20行JS代码实现贪吃蛇</title>
</head>
<body>
    <canvas id="can" width="400" height="400" style="background:black;"></canvas>
    <script>
    var sn=[42,41],dz=43,fx=1,n,ctx=document.getElementById("can").getContext("2d");
    function draw(t,c){
        ctx.fillStyle=c;
        ctx.fillRect(t%20*20,~~(t/20)*20,18,18);
    }
    document.onkeydown=function(e){fx=sn[1]-sn[0]==(n=[-1,-20,1,20][(e||event).keyCode-37]||fx)?fx:n};
    !function(){
        sn.unshift(n=sn[0]+fx);
        if(sn.indexOf(n,1)>0 || n<0||n>399||fx==1&&n%20==0||fx==-1&&n%20==19) return alert("GAME OVER");
        draw(n,"Lime");
        if(n==dz){
            while(sn.indexOf(dz=~~(Math.random()*400))>=0);
            draw(dz,"Yellow");
        }else
            draw(sn.pop(),"Black");
        setTimeout(arguments.callee,500);
    }();
    </script>
</body>
</html>
二十行简单代码参考

因为后面蛇的死亡和删除没有做好,之后找时间补充完整。。。

 index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

       *{
           margin: 0px;
           padding: 0px;
       }
       #map{
            height: 800px;
            width: 800px;
            background-color: #C0C0C0;
       }
</style>
</head>

<body>
      <div id="map">
      </div>
</body>
<script type="text/javascript" src="tools.js"></script>
<script type="text/javascript" src="food.js"></script>
<script type="text/javascript" src="snake.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="main.js"></script>



</html>
View Code

food.js

(function(){
    
    
    //保存生成的食物的数组
    var elements=[];
    
    //新建食物类的构造函数
    function Food(map,options){
        
        options=options||{};
        this.height=options.height||20;
        this.width=options.width||20;
        this.x=options.x||0;
        this.y=options.y||0;
        this.backgroundColor=options.backgroundColor||'red';
        
        //新建一个食物div
        this.div=document.createElement('div');
        map.appendChild(this.div);
        this.map=map;
        //将新建的食物存进食物数组中
        elements.push(this.div);
        
        
        //渲染食物的样式
        this.render();
    }
    
    
    
    Food.prototype.render=function(){
        
        this.div.style.height=this.height+'px';
        this.div.style.width=this.width+'px';
        this.div.style.backgroundColor=this.backgroundColor;
        this.div.style.position='absolute';
        this.random(map);
    }
    
    
    //给食物随机生成坐标
    Food.prototype.random=function(map){
        
        this.div.style.left=Tools.getRandom(0,map.offsetWidth/this.width-1)*this.width+'px';
        this.div.style.top=Tools.getRandom(0,map.offsetHeight/this.height-1)*this.height+'px';
        
    };
    
    
    
    //删除食物数组中之前生成的食物
    function remove(){
        for(var i=elements.length-1;i>=0;i--){
            elements.splice(elements[i],1);
        }
    }
    
    
    //对外暴露食物类的构造函数
    window.Food=Food;

    
    
})();
View Code

game.js

(function(){
    
    //控制整个游戏执行的逻辑
    function Game(map){
          this.food=new Food(map);
          this.snake=new Snake(map); 
    }
    
    
    
    Game.prototype.start=function(){
        
        //将食物和蛇渲染进地图中
        this.food.render(this.map);
        this.snake.render(this.map);
        
        
        
        
        //让整个蛇按照方向移动
        //一旦触碰到墙壁游戏结束
        //一旦吃到食物,蛇节部分就要增加一节
        
    };
    
    
    window.Game=Game;
    
    
    
})();
View Code

main.js

var map=document.getElementById('map');
var game=new Game(map);
game.start();
View Code

snake.js

(function(){
    
    //保存蛇的数组
    var elements=[];
    function Snake(map,options){
        
        options=options||{};
        this.height=options.height||20;
        this.width=options.width||20;
        //保存蛇的主体部分
        this.body=[
            {x:3,y:2,color:'red'},
            {x:2,y:2,color:'blue'},
            {x:1,y:2,color:'blue'},
        ];
        this.map=map;
        
        //将蛇渲染进地图map
        this.render();
    }
    
    
    Snake.prototype.render=function(){
        for(var i=0;i<this.body.length;i++){
            var div=document.createElement('div');
            this.map.appendChild(div);
            //将蛇的部分保存到elements数组中
            elements.push(div);
            div.style.height=this.height+'px';
            div.style.width=this.width+'px';
            div.style.position='absolute';
            div.style.left=this.body[i].x*this.width+'px';
            div.style.top=this.body[i].y*this.height+'px';
            div.style.backgroundColor=this.body[i].color;
            
        }
        
        
    };
    
    
    
    //对外暴露蛇的构造函数
    window.Snake=Snake;
    
    
    
})();
View Code

tools.js

var Tools={
    //随机生成[0,600]之间随机数整数
    getRandom:function(min,max){
          min = Math.ceil(min);
          max = Math.floor(max);
          return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 
    }        
        
};
View Code
posted @ 2019-09-26 17:06  菜鸟-传奇  阅读(631)  评论(0编辑  收藏  举报