Prototype 架構分析(一)

來源:互聯網
上載者:User
文章目錄
  • Class

Prototype 架構分析(一)Class

關於javascript的物件導向設計可以參看MSDN上的文章《JavaScript使用物件導向的技術建立進階 Web 應用程式》,這樣理解起來更加容易。

  • Class的聲明

Prototype的協助文檔中關於Class的介紹中有下面的例子:

var Animal = Class.create();

Animal.prototype = {

  initialize: function(name, sound) {

    this.name  = name;

    this.sound = sound;

  },

  speak: function() {

    alert(name + " says: " + sound + "!");

  }

};

var snake = new Animal("Ringneck", "hissssssssss");

snake.speak();

// -> alerts "Ringneck says: hissssssssss!"

//snake.name = "NewRingneck";

//snake.speak();

//如果更改了Animal的名字,它的speak方法仍然是初始化的狀態。

//原因就在於js的閉包原理,所以speak方法應該為

//alert(this.name + " says: " + this.sound + "!");

這裡Class.create()返回了一個函數,也就是說變數Animal是一個函數。而這個函數的功能就是調用Obj的initialize方法,從而實作類別的初始化。因此每個類必須要有initialize方法。

  • Class的繼承

Class的繼承其實就是更改對象的prototype:

//接著上面的例子

var Dog = Class.create();

//Object.extend方法返回Animal對象,並且給這個Animal增加了

//initialize方法,而根據js運行時可以知道會覆蓋先前Animal

//的initialize方法。不過這裡Dog.prototype的constructor方法沒有改變跟Animal.prototype一致。

//當然如果不用constructor方法也就可以忽略這一點了。

Dog.prototype = Object.extend(new Animal(), {

  initialize: function(name) {

    this.name  = name;

    this.sound = "woof";

  }  

});

var fido = new Dog("Fido");

fido.speak();

// -> alerts "Fido says: woof!"

聯繫我們

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