Javascript深入之建立對象的多種方式以及優缺點

來源:互聯網
上載者:User

標籤: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深入之建立對象的多種方式以及優缺點

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.