JavaScript的類定義與繼承
// 建立對象 var obj = { property:"this is property", method:function(){ return "I'm a method"; }, // toString會在對象轉為字串的時候被調用,可用作對象本身的描述 toString:function(){ return "I'm a Object"; } } // 在JavaScript規範中,任何{}建立的對象都屬於Object類,並且允許動態對象; // 為了讓JavaScript具備物件導向的實現機制,有兩個不可或缺的元素:constructor function和prototype對象 // 類名首字母大寫 function Rectanle(width,height){ // 執行個體變數前面加this this.width = width; this.height = height; // 定義方法 this.area = function(){ // 擷取執行個體變數一定要加上this return this.width * this.height; } } // JavaScript中,函數也算是一種對象,有自己的屬性和方法;使用Rectanle建立的執行個體都會三個屬性:width,height,area // JavaScript每個通過建構函式建立的對象都包含一個固定的屬性prototype function Rectanle2(width,height){ this.width = width; this.height = height; Rectanle2.prototype.area = function(){ return this.width * this.height; } } var rect = new Rectanle2(10,20); // 可以在Firefox的firebug中輸出 console.info("the rectanle area is:"+rect.area()); // 當JavaScript遇到rect.area()時,可以直接在對象上找到area這個屬性,並直接調用area()方法,如果建立了100個這樣的執行個體 // 就有100個相同的area在記憶體裡,這顯然是不合理的,如果在Rectanle的prototype中定義方法,那麼當JavaScript引擎遇到rect.area()時 // 會發現對象裡沒有這個屬性,JavaScript會繼續到rect的prototype屬性裡尋找,rect的prototype是指向Rectanle的prototype,JavaScript // 引擎在Rectanle.prototype上找到area(),就會調用這個方法,即使100個這樣的執行個體,也沒有1個area存在於記憶體中 // 定義類、類方法與類屬性 function Person(){} Person.id = 0; Person.createAccount = function(){ Person.id ++; return new Person(); } var p1 = Person.createAccount(); var p2 = Person.createAccount(); console.info("the is :"+Person.id); // JavaScript1.5版本規範中沒有抽象類別、介面和多重繼承,只有單一繼承,而繼承必須通過prototype來實現 function Person(name,email){ this.name = name; this.email = email; } Person.prototype.getInfo = function(){ return "name:"+this.name+" email:"+this.email; } function Employee(name,email,title){ // 如同Java中的super(),必須使用call明確定義scope為Employee的執行個體 Person.call(this,name,email); this.title = title; } // 如果要繼承Person,子類的prototype必須指派為父類的執行個體 Employee.prototype = new Person(); var employee = new Employee("fuyuwei","fuyuwei@outlook.com","info"); console.info("Employee info is:"+employee.getInfo());