js创建对象的几种方式

一、new 操作符 + Object 创建对象

var person = new Object();
person.name = "lisi";
person.age = 21;
person.family = ["lida","lier","wangwu"];
person.say = function(){
alert(this.name);
}

二、字面式创建对象

var person ={
  name: "lisi",
  age: 21,
  family: ["lida","lier","wangwu"],
  say: function(){
    alert(this.name);
  }
};

三、工厂模式

function createPerson(name,age,family) {
    var o = new Object();
    o.name = name;
    o.age = age;
    o.family = family;
    o.say = function(){
        alert(this.name);
    }
    return o;
}

四、构造函数模式

function Person(name,age,family) {
    this.name = name;
    this.age = age;
    this.family = family;
    this.say = function(){
        alert(this.name);
    }
}

五、原型模式

function Person() {
}
Person.prototype.name = "lisi";
Person.prototype.age = 21;
Person.prototype.family = ["lida","lier","wangwu"];
Person.prototype.say = function(){
    alert(this.name);
};
var person1 = new Person();        //创建一个实例person1
console.log(person1.name);        //lisi

六、混合模式(构造函数模式+原型模式)

posted @ 2020-09-15 09:18  爱喝可乐的靓仔  阅读(155)  评论(0编辑  收藏  举报