依舊是惡補js基礎,上代碼:dom
一、定義父類及父類方法函數
function Animal(){ this.name = "動物"; } Animal.prototype.eat = function(food){ alert('eat ' + food); }
二、定義子類測試
function Ferret(){ this.name = "雪貂";
//this.type = "leixing";//此處,若是定義了type,會覆蓋下面prototype.type的「domestic」
//說明一個機制,調用Ferret().type的時候,先尋找對象自有屬性,再查找原型鏈內屬性
}
三、原型鏈繼承核心this
function fn(){ //中間函數,防止每次建立對象都要new }
//父類的屬性與方法經過prototype傳遞給中間函數 fn.prototype = Animal.prototype;
//中間函數的實例將父類的屬性與方法傳遞給子類的prototype Ferret.prototype = new fn();
四、擴展子類spa
//爲全部Ferret實例定義type屬性 Ferret.prototype.type = "domestic"; Ferret.prototype.eat = function(food){ //子類執行父類的方法 Animal.prototype.eat.call(this,food); //子類的擴展邏輯 alert(this.type + ' eat ' + food); }
五、測試繼承結果prototype
var animal = new Animal(); var ferret = new Ferret();
animal instanceof Animal // true
animal instanceof Ferret // false
ferret instanceof Ferret // true
ferret instanceof Animal // true 此處,子類是父類的實例爲true,說明繼承成功~
ferret.eat('meat');//一、alert(eat meat); 二、alert(domestic eat meat);
如下是一些囉嗦:code
var a = { a: 'b', c: 'd' }; function a1(){ this.a = 'b'; this.c = 'd'; }
a instanceof Object // true
a1 instanceof Object // true
由此能夠看出,a與a1均屬於對象,那麼,有什麼區別呢對象
a.prototype == undifiend // true
a1.prototype == undefined // false
typeof a == "object" // true
typeof a1 == "function" // true
Object.keys(a) // ["a", "c"]
Object.keys(a1) // []
a僅僅是一個單純的key&value,沒有構造函數,屬於【引用類型】blog
而a1則有prototype,能夠實現繼承,經過Object.keys()能夠看出,a1身爲一個Object,不存在key&value,屬於【值類型】繼承
V8中的繼承:
function Animal(){} function Ferret(){} Ferret.prototype.__proto__ = Animal.prototype// 父類將屬性傳遞給子類