一,類與實例函數
1,類的聲明優化
/** *類的聲明 */ function Animal(name) { this.name = name; } /** *ES6中class的聲明 */ class Animal2 {//類的聲明 constructor(name) {//構造函數 this.name = name; } }
2,生成實例this
/** *實例類的對象/實例化(經過new實例化,若是沒有參數,能夠省略括號,但不建議這麼作) */ console.log(new Animal(),new Animal2());
二,類與繼承spa
1,如何實現繼承prototype
借用構造函數,使用原型鏈,組合繼承code
2,繼承的幾種方式對象
(1)藉助構造函數實現繼承blog
/** * 藉助構造函數實現繼承 */ function Parent1() { this.name = 'parent1'; } Parent1.prototype.say = function() { //構造函數繼承沒法繼承原型對象上的屬性 !!! }; function Child1() { Parent1.call(this); this.type = 'child1'; } console.log(new Child1()); console.log(new Child1().say()) //(intermediate value).say is not a function !!!
(2)藉助原型鏈實現繼承繼承
/** * 藉助原型鏈實現繼承 */ function Parent2() { this.name = 'parent2'; this.play = [1, 2, 3]; } function Child2() { this.type = 'child2'; } Child2.prototype = new Parent2(); var s1 = new Child2(); var s2 = new Child2(); console.log(s1.play, s2.play); //[1, 2, 3] [1, 2, 3] s1.play.push(4); console.log(s1.play); //[1, 2, 3, 4] !!! console.log(s2.play); //[1, 2, 3, 4] !!! console.log(s1.constructor,s2.constructor); //Parent2 Parent2 !!!
(3)組合方式原型鏈
/** * 組合方式 */ 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); //[1, 2, 3, 4] console.log(s2.play); //[1, 2, 3] console.log(s3.constructor); //Parent3 !!!
(4)組合方式優化1
/** * 組合繼承的優化1 */ function Parent4() { this.name = 'parent4'; this.play = [1, 2, 3]; } function Child4() { Parent4.call(this); this.type = 'child4'; } Child4.prototype = Parent4.prototype; var s5 = new Child4(); var s6 = new Child4(); console.log(s5, s6); s5.play.push(4); console.log(s5.play); //[1, 2, 3, 4] console.log(s6.play); //[1, 2, 3] console.log(s5 instanceof Child4, s5 instanceof Parent4); //true true console.log(s5.constructor); //Parent4 !!!
(5)組合方式優化2
/** * 組合繼承的優化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(); var p5 = new Parent5(); console.log(s7.constructor); //Child5
附:Object.create的實現方式
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
未完待續...