標籤:java str 執行個體 方法 getname 使用 ... his this
1.原廠模式
function createPerson(name) { var o = new Object(); o.name = name; o.getName = function() { console.log(this.name) }; return o;}var person1 = createPerson(‘kevin‘)
缺點:對象無法識別,因為所以的執行個體都指向一個原型
2.建構函式模式
function Person(name) { this.name = name; this.getName = function() { console.log(this.name); }}var person1 = new Person(‘kevin‘)
優點:執行個體可以識別為一個特定的類型
缺點:每次建立執行個體時,每個方法都要被建立一次
2.1建構函式模式最佳化
function Person(name) { this.name = name; this.getName = getName;}function getName() { console.log(this.name)}var person1 = new Person(‘kevin‘)
優點:解決了每個方法都要被重新建立的問題
缺點:這叫啥封裝...
3.原型模式
function Person(name) {}Person.prototype.name = ‘kevin‘;Person.prototype.getName = function() { console.log(this.name);}var person1 = new Person()
優點:方法不會重新建立
缺點:1.所有的屬性和方法都共用 2.不能初始化參數
3.1原型模式最佳化
function Person(name) {}Person.prototype = { name: ‘kevin‘, getName: function(){ console.log(this.name) }}var person1 = new Person()
優點:封裝性好一點
缺點:重寫了原型,丟失了 constructor屬性
3.2 原型模式最佳化
function Person(name) {}Person.prototype = { constructor: Person, name:‘kevin‘, getName: function() { console.log(this.name) }}var person1 = new Person()
優點:執行個體可以通過constructor屬性找到所屬建構函式
缺點:原型模式該有的缺點還是有
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) } } }}var person1 = new Person(‘kevin‘)var person2 = new Person(‘marven‘)person1.getName() // 報錯 並沒有該方法person2.getName() // 注釋掉上面的代碼,這句是可以執行的
Javascript深入之建立對象的多種方式以及優缺點