JavaScript 创建对象的三种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/coderinchina/article/details/89414457

第一种字面量的方式创建对象

var person={
        name:"zhouguizhi",
        age:18,
        eat:function () {
            console.log("中午吃鱼")
        },
        study:function () {
            console.log("晚上学习JavaScript语法")
        }
    }

调用:

 person.eat();
 person.study();

第二种方式 调用系统的构造函数

  var person = new Object();
   person.name="zhouguizhi";
   person.age = 19;
    person.getName = function(){
       console.log("name="+this.name);
    }
    person.getAge = function(){
        console.log("age="+this.age);
    }

调用方式

 person.getAge();
 person.getName();

第三种方式  自定义构造函数

 function Person(name,age,sex) {
       this.name = name;
       this.age = age;
       this.sex = sex;
       this.getName = function () {
           console.log("我叫:"+this.name)
       }
       this.getAge = function () {
           console.log("我今年:"+this.age)
       }
   }

这种创建对象的方式和Java语法最像

调用方式

var person = new Person("zhouguizhi",18,"男");
person.getName();
person.getAge();

猜你喜欢

转载自blog.csdn.net/coderinchina/article/details/89414457