接上文:es6
function Animal (){ this.name="name"; } es6: class Animal2{ constructor(){ this.name="name"; } }
缺點:沒法繼承來自Parent1的原型上的東西,只能部分繼承函數
>原型鏈繼承測試
function Parent4 () { this.name = 'parent4'; this.play = [1, 2, 3]; } function Child4 () { Parent4.call(this); this.type = 'child4'; } Child4.prototype = Parent4.prototype; Child4.prototype.constructor=Child4; var s5 = new Child4(); var s6 = new Child4(); console.log(s5, s6); console.log(s5 instanceof Child4, s5 instanceof Parent4); console.log(s5.constructor);
>終極優化優化
var o=Object.create(parent)是把參數parent當作原型對象傳給o的,因此o並不具有parent的屬性,可是o的__proto__具備,由於o.__proto__===parentthis
總結:原型鏈繼承因爲new的時候是把原型對象上的屬性複製給新對象,因而新對象至關於有兩個相同屬性,若是新對象爲o,那麼他既有o.name,又有o.__proto__.name,修改兩個的時 候互不影響,可是會影響原型鏈就是原型對象的.prototype,繼而影響全部new出來的新對象spa
若有錯誤,請多指正prototype