類的聲明es6
/** * 類的聲明,採用構造函數聲明 */ var Animal = function () { this.name = 'Animal'; }; /** * es6中class的聲明 */ class Animal2 { constructor () { this.name = 'Animal2'; } }
生成實例app
/** * 實例化 */ console.log(new Animal(), new Animal2());
繼承的幾種方式函數
實現了部分繼承,只能繼承父類構造函數體內的屬性;父類的原型對象上的方法不能繼承。優化
/** * 藉助構造函數實現繼承 */ function Parent1 () { this.name = 'parent1'; } Parent1.prototype.say = function () { //Parent1 原型鏈上的方法並無被 Child1 所繼承 }; function Child1 () { Parent1.call(this);//apply;改變函數運行的上下文(將父級的構造函數this指向子構造函數的實例上) this.type = 'child1'; } console.log(new Child1(), new Child1().say());//Uncaught TypeError: (intermediate value).say is not a function
彌補了構造函數繼承的不足,可是繼承後原型鏈上的原型對象是共用的,改變一個其他的也都跟着改變。this
/** * 藉助原型鏈實現繼承 */ function Parent2 () { this.name = 'parent2'; this.play = [1, 2, 3]; } function Child2 () { this.type = 'child2'; } Child2.prototype = new Parent2();//new Child2().__proto__===Child2.prototype var s1 = new Child2(); var s2 = new Child2(); console.log(s1.play, s2.play);//(3) [1, 2, 3] (3) [1, 2, 3] s1.play.push(4); console.log(s1.play, s2.play);//(4) [1, 2, 3, 4] (4) [1, 2, 3, 4]
實現向對象繼承的通用方式。(缺點:在實例化1個子類的時候,父類的構造函數執行了2次)prototype
/** * 組合方式 */ function Parent3 () { this.name = 'parent3'; this.play = [1, 2, 3]; } function Child3 () { Parent3.call(this);//在子構造函數中執行父級構造函數 this.type = 'child3'; } Child3.prototype = new Parent3(); var s3 = new Child3(); var s4 = new Child3(); s3.play.push(4); console.log(s3.play, s4.play);//(4) [1, 2, 3, 4] (3) [1, 2, 3]
優勢:實例化1個子類的時候,父類的構造函數執行了1次;
不足:沒法區分一個對象是 直接 由子類實例化的仍是經過父類實例化的。code
/** * 組合繼承的優化1 * @type {String} */ function Parent4 () { this.name = 'parent4'; this.play = [1, 2, 3]; } function Child4 () { Parent4.call(this); this.type = 'child4'; } Child4.prototype = Parent4.prototype;//實例化1個子類的時候,父類的構造函數執行了1次 var s5 = new Child4(); var s6 = new Child4(); console.log(s5, s6);//Child4 {name: "parent4", play: Array(3), type: "child4"} Child4 {name: "parent4", play: Array(3), type: "child4"} console.log(s5 instanceof Child4, s5 instanceof Parent4);//true true console.log(s5.constructor); /** ƒ Parent4() { this.name = 'parent4'; this.play = [1, 2, 3]; } */
完美寫法。經過 Object.create()
建立一箇中間對象,再修改子類實例的構造函數。對象
/** * 組合繼承的優化2 */ function Parent5 () { this.name = 'parent5'; this.play = [1, 2, 3]; } function Child5 () { Parent5.call(this); this.type = 'child5'; } Child5.prototype = Object.create(Parent5.prototype); Child5.prototype.constructor=Child5; var s7=new Child5(); console.log(s7 instanceof Child5,s7 instanceof Parent5);//true true s7.constructor /** ƒ Child5() { Parent5.call(this); this.type = 'child5'; } */