function Parent(){
//原料 var Child=new Object();//建立對象
//加工 Child.name="aaa";//對象屬性 Child.age="30"; child.fn=fn; //對象方法
//出廠
return Child; //必定要返回該對象 }; var fn=function(){ return "111"; }; var x=Parent();//建立實例 alert(x.name);
說明:html
1.在函數中定義對象,並定義對象的各類屬性,雖然屬性能夠爲方法,可是建議將屬性爲方法的屬性定義到函數以外,這樣能夠避免重複建立該方法;函數
2.引用該對象的時候,這裏使用的是 var x = Parent()而不是 var x = new Parent();由於後者會可能出現不少問題(前者也成爲工廠經典方式,後者稱之爲混合工廠方式),不推薦使用new的方式使用該對象;this
3.在函數的最後返回該對象;spa
4.不推薦使用這種方式建立對象,但應該瞭解prototype
5.工做原理很像是在工廠工做的一個流程,那就是:原料、加工、出廠。code
function Parent(){
this.name="aaa";//對象屬性
this.age="30";
this.fn=fn; //對象方法
}
var fn=function(){
return "111";
}
var x=new Parent();//建立實例
alert(x.name);
說明:htm
1.與工廠方式相比,使用構造函數方式建立對象,無需在函數內部重建建立對象,而使用this指代,並而函數無需明確return
2.同工廠模式同樣,雖然屬性的值能夠爲方法,扔建議將該方法定義在函數以外
3.一樣的,不推薦使用這種方式建立對象,但仍須要瞭解對象
function Parent(){
Parent.prototype.name="aaa";//對象屬性
Parent.prototype.age="30";
Parent.prototype.fn=fn; //對象方法
}
var fn=function(){
return "111";
}
var x=new Parent();//建立實例
alert(x.name);
說明:
1.函數中不對屬性進行定義
2.利用prototype屬性對屬性進行定義
3.一樣的,不推薦使用這樣方式建立對象blog
function Parent(){ //構造函數加屬性
this.name="aaa";
this.age=3;
};
Parent.prototype.fn=function(){ //原型上加方法
return this.name;
};
var x =new Parent();
alert(x.fn());
說明:原型
1.該模式是指混合搭配使用構造函數方式和原型方式;
2.將全部屬性不是方法的屬性定義在函數中(構造函數加屬性);將全部屬性值爲方法的屬性利用prototype在函數以外定義(原型上掛方法);
3.推薦使用這樣方式建立對象;
function Parent(){
this.name="aaa";
this.age=30;
if(typeof Parent._fn=="undefined"){
Parent.prototype.fn=function(){
return this.name;
}
Parent._fn=true;
}
};
var x =new Parent();
alert(x.fn());
說明:
1.動態原型方式能夠理解爲混合構造函數,原型方式的一個特例
2.該模式中,屬性爲方法的屬性直接在函數中進行了定義,可是由於
if(typeof Parent._fn=="undefined"){ Parent._fn=true; } 從而保證建立該對象的實例時,屬性的方法不會被重複建立