如何创建JavaScript对象

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
   </head>
    <body>
        <script>
            //直接创建方式
            // var student = new Object();
            // student.name = "Jim";
            // student.mibile = "110";
            // student.doHomework = function (){
            //     console.log(this.name+"正在做作业。。。");
            // }
            // student.doHomework();

            //对象初始化器方式(常用)
            // var student = {
            //     "name": "Jack",
            //     mibile : "119",
            //     doHomework:function (){
            //         console.log(this.name+"正在做题。。。");//this不能省
            //     }
            // }
            // student.doHomework();

            //函数式:可以方便的创建多个不同的对象
            // function Student(name,mobile){
            //     this.name = name;
            //     this.mobile = mobile;
            //     this.doHomework = function(){
            //         console.log(this.name+this.mobile+"在写");
            //     }
            // }
            // var student = new Student("Jan","111");
            // student.doHomework();

            //原型式:不能方便的创建多个对象;实现了自定义方法和构造方法的分离
            // function Student(){};
            // Student.prototype.name = "Jack";
            // Student.prototype.mobile = "120";
            // Student.prototype.doHomework=function(){
            //     console.log(this.name+this.mobile+"写写写");
            // }
            // var student = new Student();
            // student.doHomework();
            // student = new Student();
            // student.name="LiLy";
            // student.doHomework();

            //混合式(函数式+原型式)(常用)
            function Student(name,mobile){//变量里不加var,为全局变量,print()里的变量不能用var关键字修饰
                this.name = name;
                this.mobile = mobile;
            }
            Student.prototype.callName = function (){
                console.log(this.name+this.mobile+"正在打电话");
            }
            var student = new Student('liMing',"191");
            student.callName();
        </script>
    </body>
</html>

 

posted @ 2021-06-04 15:24  程序新人小刘  阅读(60)  评论(0)    收藏  举报