js物件導向編程-base基類-Dean Edwards

來源:互聯網
上載者:User

之前用js總是一個個的function,看見別人用js物件導向的寫法,有點不懂,這幾天看見同事直接用一個很小的base.js及簡單實現了javascript的物件導向,並輕鬆實現了繼承,

base.js擷取地址:http://dean.edwards.name/base/Base.js

/**
 * 建立類
 * 通過調用Base類裡面的extend方法,可以建立類:
 */
var Animal = Base.extend({
 name:"", //成員變數
 //構造方法
 constructor:function(name){
  this.name = name;
 },
 //方法
 eat:function(){
  this.say("hello!");
 },
 say:function(message){
  alert(this.name+":"+message);
 }
});
//使用方法
new Animal("tom").eat(); //alert:tom:hello!

/**
 * 繼承
 * extend:調用這個方法,可以用另一個介面來擴充一個對象
 * base:如果某個方法被重載了,通過base方法可以訪問被重載方法
 *
 * 所有使用這種方式建立的類會繼承extend方法,所以我們可以簡單的為Animal類建立子類
 */
var Cat = Animal.extend({
 eat:function(food){
  if(food instanceof Mouse){
   this.base(); //調用被重載的方法
  } else {
   this.say("Yuk! I only eat mice.");
  }
 }
});

var Mouse = Animal.extend();

new Cat('Cat').eat(new Mouse()); //alert:Cat:hello!
new Cat('Cat').eat('test');   //alert:Cat:Yuk! I only eat mice. 

/**
 * 執行個體方法、類方法比較
 * 如果你定義了一個叫做init的類方法 (不是執行個體方法) ,它會在類建立的時候自動的調用。
 * 在原型構造階段(衍生子類)建構函式永遠不會被調用
 */
var Shape = Base.extend({
 constructor:function(x,y){
  alert(x+y);
 }
});
var Circle = Shape.extend({ // instance interface
   constructor: function(x, y, radius) {
     this.base(x, y);
     this.radius = radius;
   },
   radius: 0,
   
   getCircumference: function() {
     return 2 * Circle.PI * this.radius;
   }
 },
 { // class interface
   PI: 3.14,
   init:function(){ //類方法 在類建立的時候就會被調用
   alert(2);
   }
 });
//alert:先 2 在 3 後 18.84
alert(new Circle(1,2,3).getCircumference());

聯繫我們

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