- 工廠模式
發(fā)明一種函數(shù),用函數(shù)來封裝以特定接口創(chuàng)建對象的細(xì)節(jié)。
function createPerson(name,age,job) {
var o=new Object();
o.name=name;
o.age=age;
o.job=job;
o.sayName=function(){
alert(this.name)
}
return o;
}
- 構(gòu)造函數(shù)模式
function createPerson(name,age,job) {
this.name=name;
this.age=age;
this.job=job;
this.sayName=function(){
alert(this.name)
}
}
不同之處:沒有顯式創(chuàng)建對象
直接將屬性和方法賦給this對象
沒有return語句
使用new操作符,會經(jīng)歷四個步驟
1.創(chuàng)建已給新對象
2.將構(gòu)造函數(shù)的作用域賦值給新對象
3.執(zhí)行構(gòu)造函數(shù)中的代碼
4.返回新對象
var new1 = function(fun){
var newObj = Object.create(fun.prototype);
var returnObj = fun.call(newObj);
if(typeof returnObj === 'object'){
return returnObj
}else{
return newObj
}
}
- 原型模式
創(chuàng)建的每個函數(shù)都有一個prototype(原型)屬性,這個屬性是一個指針,指向一個對象。
function Person(){
}
Person.prototype.name='FBB';
Person.prototype.age=12;
Person.prototype.job='Student';
Person.prototype.sayName=function(){
alert(this.name)
}
Person.prototype.constructor==Person
使用hasOwnProperty()方法來判斷什么時候訪問實(shí)例屬性,什么時候訪問原型屬性。
但是原型中所有的屬性都是共享的,這種共享適合函數(shù),不太適合包含引用類型值的屬性。
- 組合使用構(gòu)造函數(shù)模式和原型模式
構(gòu)造函數(shù)模式用于定義實(shí)例屬性,原型模式用于定義方法和共享屬性。
function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
this.friends=['TQQ','LWZ'];
}
Person.prototype={
constructor:Person,
sayName:function(){
alert(this.name)
}
}
實(shí)例屬性都是在構(gòu)造函數(shù)中定義的,而所有的實(shí)例共享屬性都在原型中定義。