工廠模式
function createPerson(name){
var o = new Object();
o.name = name;
o.getName = function(){
console.log(this.name);
};
return o;
}
var person = createPerson('johe');
缺點:對象無法識別郑临,都指向一個原型Object,并且每個實例的getName函數(shù)的引用地址不同
構(gòu)造函數(shù)模式
function Person(name){
this.name = name;
this.getName = function(){
console.log(this.name);
}
}
var person1 = new Person('johe');
優(yōu)點:實例可以識別為一個特定的類型屑宠,都指向Person.prototype
缺點:每次創(chuàng)建實例時,getName方法都要被創(chuàng)建一次躺翻,即每個實例的getName函數(shù)的引用地址不同
構(gòu)造函數(shù)優(yōu)化
function Person(name){
this.name = name;
this.getName = getName
}
function getName(){
console.log(this.name)
}
優(yōu)點:所有g(shù)etName都指向一個地址
缺點:封裝不好
原型模式
function Person(name){
}
Person.prototype.name = 'johe'
Person.prototype.getName = function(){
console.log(this.name);
}
var person1 = new Person()
優(yōu)點:方法不會被重新創(chuàng)建
缺點:所有屬性和方法都共享(實例修改屬性會影響到其他實例)秋柄,并且不能初始化參數(shù)
原型模式優(yōu)化
function Person(name){
}
Person.prototype = {
constructor:Person,
name:'johe',
getName:function(){
console.log(this.name)
}
}
var person1 = new Person()
與原型模式相比,封裝性好了一點
組合模式
構(gòu)造函數(shù)模式和原型模式雙劍合璧
function Person(name){
this.name = name;
}
Person.prototype = {
constructor:Person,
getName:function(){
console.log(this.name)
}
}
優(yōu)點:屬性不會被共享省店,方法共享,即構(gòu)造函數(shù)內(nèi)初始化實例屬性和方法懦傍,原型內(nèi)初始化共享屬性和方法
缺點:封裝性不夠好