javascript 繼承 , 老生長談的東西, 大家應該都很熟悉了, 平時工作基本不會直接使用, 這段時間不忙, 所以補習了下相關基礎知識 ,自己動手實踐, 加深理解:
基類定義如下:
// base class function Animal(t) { if(typeof t==='string') this.type=t; else { if(t) this.type=t.toString(); else this.type='Animal' } this.speak=function(str) { if(str) console.log(this.type+' said '+str); else throw "please specify what you want to say!"; } }
1.原型繼承 (javascript 類庫本身基於原型繼承)
String, Number , Boolean 這三大原始類型 我們可以很直接的通過prototype 檢查到他們繼承自Object.
Date, RegExp ,Array 這三應該是間接繼承了Object, 他們的prototype屬性很特殊 :
Date.prototype =Invalid Date
RegExp.prototype=/(?:)/
Array.prototype=[]
原型繼承代碼如下: (可以看到Mokey 原型鏈上的Animal和Object)
// Monkey : Animal function Monkey(name,age) { this.name=name; this.age=age; } Monkey.prototype=new Animal('Monkey'); // Example 01 var m=new Monkey('codeMonkey',10); /* Monkey: age: 10 name: "codeMonkey" __proto__: Animal speak: function (str) type: "Monkey" __proto__: Animal constructor: function Animal(t) __proto__: Object */ console.log(m.type); // Monkey console.log(m.name); // codeMonkey console.log(m.age); // 10 m.speak('hello world') // Monkey said hello world
2. 調用父類建構函式 ( 通過傳遞子類的this指標 , 將原本是父類的公開成員直接添加到了子類中,從子類原型鏈中無法看出繼承關係)
// Human:Animal function Human(id,name) { // call base class's constuctor function Animal.call(this,'Human'); this.id=id; this.name=name; } var h=new Human(1,'leon'); /* id: 1 name: "leon" speak: function (str) type: "Human" __proto__: Human constructor: function Human(id,name) __proto__: Object */ h.speak('hello world'); // Human said hello world console.log(h.type); // Human