js:對象的建立(基於組合和動態原型)

來源:互聯網
上載者:User

標籤:js

基於原型的建立雖然可以有效地完成封裝,但是依然存在如下問題:
1.無法通過建構函式來設定屬性值
2.當屬性中有參考型別變數時,可能存在變數值重複

function Person(){

}

Person.prototype = {
  constructor:Person,
  name:"Leon",
  age:30,
  friends:["Ada","Chris"],
  say:function(){
    alert(this.name+"["+this.friends+"]");
  }
}
var p1 = new Person();
p1.name = "John";
p1.say();  //John[Ada,Chris]
var p2 = new Person();
p2.say();  //Leon[Ada,Chris]

p1.friends.push("Mike");
//此時原型中就多了一個Mike,這就是原型所帶來的第二個問題
p2.say();  //Leon[Ada,Chris,Mike]

/**為瞭解決原型所帶來的問題,我們可以通過組合建構函式和原型來實現對象的建立
 * 將屬性在建構函式中定義,將方法在原型中定義
 */
function Person(name,age,friends){
  //屬性在建構函式中定義
  this.name = name;
  this.age = age;
  this.friends = friends;
}
Person.prototype = {
  constructor:Person, 
  //方法在原型中定義
  say:function(){
    alert(this.name+"["+this.friends+"]");
  }
}

//此時所有的屬性都是儲存在自己的空間中
var p1 = new Person("Leon",23,["Ada","Chris"]);
p1.name = "John";
p1.friends.push("Mike");
p1.say();  //John[Ada,Chris,Mike]
var p2 = new Person("Ada",33,["Leon"]);
p2.say();  //Ada[Leon]

為了讓定義的方式更加符合Java的需求,就把定義方法的原型代碼放置到Person這個建構函式中
function Person(name,age,friends){
  //屬性在建構函式中定義
  this.name = name;
  this.age = age;
  this.friends = friends;
  //不能使用重寫的方式定義
  /*Person.prototype = {
    constructor:Person, 
    //方法在原型中定義
    say:function(){
      alert(this.name+"["+this.friends+"]");
    }
  }*/
  
  if(typeof Person.prototype.say){
    //但是這也會引起一個問題:那就是每new一個對象,say方法就定義一次 所以我們要在上面加上if條件
    Person.prototype.say = function(){
      alert(this.name+"["+this.friends+"]");
    }
  }
}

原創文章如轉載,請註明出處,本文首發於csdn網站:http://blog.csdn.net/magneto7/article/details/24934149

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.