创建对象的多种方式
// 1. 工廠模式
//缺點:對象無法識別,因為原型都指向Object
function pe() {var o = new Object();o.name = name;o.getname = function() {console.log(this.name)}return o
}// 2. 構造函數模式
// 優點:實例可以識別為一個特定的類型
// 缺點:每次創建實例每個方法都要被創建一次
function Person(name) {this.name = name;this.getName = function() {console.log(this.name);};}
var person = new Person('zhansan');// 2.1 構造函數模式優化
// 優點:解決了每個方法都要被重新創建的問題
// 缺點:這叫啥封裝……
function Person(name) {this.name = name;this.getName = getName;}function getName() {console.log(this.name);
}
var person = new Person('zhansan');// 3. 原型模式
// 優點:方法不會重新創建
// 缺點:1. 所有的屬性和方法都共享 2. 不能初始化參數
function Person(name) {};
Person.prototype.name = 'keivn';
Person.prototype.getName = function() {console.log(this.name);
};var person1 = new Person();// 3.1 原型模式優化
// 優點:封裝性好了一點
// 缺點:重寫了原型,丟失了constructor屬性
function Person(name) {};
Person.prototype = {name: 'kevin',getName: function() {console.log(this.name);}
};var person1 = new Person();// 3.2 原型模式優化
// 優點:實例可以通過constructor屬性找到所屬構造函數
// 缺點:原型模式該有的缺點還是有
function Person(name) {}Person.prototype = {constructor: Person,name: 'kevin',getName: function() {console.log(this.name);}
};var person1 = new Person();// 4. 組合模式
// 優點:該共享的共享,該私有的私有,使用最廣泛的方式
// 缺點:有的人就是希望全部寫在一起,即更好的封裝性
function Person(name) {this.name = name;
}Person.prototype = {constructor: Person,getName: function() {console.log(this.name);}
};var person1 = new Person();// 4.1 動態原型模式
// 注意:使用動態原型模式時,不能用對象字面量重寫原型
function Person(name) {this.name = name;if (typeof this.getName != "function") {Person.prototype.getName = function() {console.log(this.name);}}
}var person1 = new Person();
// 如果你就是想用字面量方式寫代碼,可以嘗試下這種:
function Person(name) {this.name = name;if (typeof this.getName != "function") {Person.prototype = {constructor: Person,getName: function() {console.log(this.name);}}return new Person(name);}
}var person1 = new Person('kevin');
var person2 = new Person('daisy');
轉載于:https://www.cnblogs.com/xzma/p/7987931.html
總結
- 上一篇: 存储基础知识 - 磁盘寻址(CHS寻址方
- 下一篇: 按阅读习惯来高效排列字符串的脚本