- 对象字面量
let obj = {};
- 构造函数
let obj = new Object();
- 工厂模式
优点:解决了重复实例化相似对象的问题,避免了代码冗余 ;缺点:不能识别对象的类型function createObj(name,sex,age){ var obj = new Object(); obj.name = name; obj.sex = sex; obj.age = age; obj.sayName = function(){ console.log(this.name); } return obj; } var person = createObj("CD","boy",21); console.log(typeof person);//object //无法判断person是object的实例还是createObj的实例 console.log(person instanceof Object); //true console.log(person instanceof createObj); //false,显然是错误的
- 构造函数模式
function createObj(name,age,sex){ this.name = name; this.age = age; this.sex = sex; this.saySex = function(){ alert(this.sex); } } var person = new createObj("CD",21,"boy"); console.log(person instanceof Object); //true console.log(person instanceof createObj); //true
优点:没有显式地创建对象,而是将属性和方法直接赋给了this对象;
缺点:每个方法都要在实例上重新创建一次
-
原型模式
function createObj(name,sex,age){ createObj.prototype.name = name; createObj.prototype.sex = sex; createObj.prototype.age = age; createObj.prototype.sayAge = function(){ alert(this.age); } } //为了简洁,可以写成: function createObj(name,sex,age){}; createObj.prototype = { constructor:obj, name:name, sex:sex, age:age, sayAge:function(){ alert(this.age); } }
优点:所有的实例都可以共享定义在原型上的属性和方法;
缺点: 所有的对象共享构造函数原型中的属性和方法 ,且constructor不再指向obj
-
混合模式(构造函数模式+原型模式)
//不共享的内容使用构造函数模式 createObj = function(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } //共享的内容使用原型模式 createObj.prototype.say = function(){ alert("hello world"); }
-
动态原型模式(据说很完美~)
function createObj(name,age,sex){ this.name = name; this.age = age; this.sex = sex; if(typeof this.say != "function"){ createObj.prototype = function(){ alert("hello world"); } } }
-
寄生构造函数模式(构造函数模式+工厂模式)、稳妥构造函数模式