首页 > Web开发 > 详细

js创建对象的几种方式

时间:2020-09-15 10:59:51      阅读:122      评论:0      收藏:0      [点我收藏+]

一、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

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

js创建对象的几种方式

原文:https://www.cnblogs.com/loveliang/p/13671285.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!