对象字面量
var obj1 = {
name : "suoz",
age : 20,
hobby : function(){
console.log('I like run');
}
};
var obj2 = {
name : "张三",
age : 22,
hobby : function(){
console.log('I like swim');
}
};
缺点 :如果创建多个对象,复用性差,造成代码冗余
使用内置构造函数
var obj1 = new Object();
obj1.name = "suoz";
obj.age = 20;
obj1.hobby = function(){
console.log('I like run');
};
var obj2 = new Object();
obj1.name = "张三";
obj.age = 22;
obj1.hobby = function(){
console.log('I like swim');
};
缺点:创建的对象是空对象,需要手动为对象添加属性,创建多个对象导致复用,代码冗余
工厂模式
function createObj(name,age,sport){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.hobby = function(){
console.log("I like" + sport);
};
}
var obj1 = createObj('suoz',20,'run');
var obj2 = createObj('张三',22,'swim');
缺点:使用工厂模式能够创建一个包含所有信息的对象,可以无数次的调用的这个函数。虽然其解决了创建多个相似对象的问题,但却没有解决对象识别的问题(即如何得知一个对象的类型)
使用自定义构造函数
function CreateObj(name,age,sport){
this.name = name;
this.age = age;
this.hobby = function(){
console.log("I like" + this.sport);
};
}
var obj1 = new CreateObj('suoz',20,'run');
var obj2 = new CreateObj('张三',22,'swim');
构造(constructor)函数的执行步骤:
1. 使用new关键字创建对象
2. 调用构造函数,将new创建出来的对象赋值给构造函数内的this
3. 执行构造函数内部代码
4. 默认返回新创建出来的这个对象
缺点:如果在构造函数内部定义函数,那么每次创建一个对象,就会重新创建该函数,由于函数内部代码相同,导致了资源浪费
注:为了解决这个问题,应该特定类型对象的实例共享该函数。
原型模式
function CreateObj(){}
CreateObj.prototype.name = "suoz";
CreateObj.prototype.arr = ["20","student"];
CreateObj.prototype.getName = function(){
alert(this.name);
};
var obj1 = new CreateObj();
var obj2 = new CreateObj();
console.log(obj2.arr); //20,student
obj1.arr.push("run");
console.log(obj2.arr); //20,student,run
优点:解决了构造函数复用性差的问题
缺点:显然,如果原型对象包含引用类型的值时,对象之间调用该属性,会互相影响(该属性是共享的);
组合模式
function createObj(name,age){
this.name = name;
this.age = age;
}
CreateObj.prototype.hobby = "run";
CreateObj.prototype.getName = function(){
alert(this.name);
};
var obj1 = new CreateObj("suoz","20");
var obj2 = new CreateObj("lisi","18");
obj1.getName(); //"suoz"
obj2.getName(); //"lisi"
优点:拥有构造函数模式和原型模式的优点
缺点:封装性差
动态原型模式
function createObj(name,age){
this.name = name;
this.age = age;
if(typeof getName != 'function'){
createObj.prototype.getName=function(){
alert(this.name);
};
}
}
优点:解决了组合模式的封装性差问题
其它模式:
寄生构造函数模式
稳妥构造函数模式