1. 程式人生 > >JS中創造構建函數的方法

JS中創造構建函數的方法

blog 構造函數 span prot logs 一模一樣 原型 pre pan

1.工廠模式

1 function CreatObject(){
2     var obj = new Object();
3     obj.name = "zackbee";
4     obj.sex = "unknow";
5     return zackbee;
6 }

2.構造函數模式

1 function CreatObject(){
2     this.name ="zackbee";
3     this.sex = "unknow";
4 }
5 var obj = new CreatObject;

3.原型模式

1 function CreatObject(){
2 } 3 CreatObject.prototype.name = "zackbee"; 4 CreatObject.prototype.sex = "unknow"; 5 var obj = new CreatObject();

4.原型模式重構原型(有坑)

1 function CreatObject(){
2 }
3 CreatObject.prototype = {
4    name : "zackbee",
5    sex : "unknow" 
6 };

  1.如果先創建實例再使用這樣的方法,實例中的prototype與構建函數的prototype不對應(詳情參考高程三p155)

5.組合使用構造函數模式以及原型模式

  略

6.動態原型模式

  如題,略

7.寄生構造函數模式

  代碼與工廠一模一樣,不推薦

8.穩妥模式(適用於安全環境)

  參考高程三p161

JS中創造構建函數的方法