當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS继承的应用案例
1、原型鏈繼承
子類的原型指向父類的實例,這就是原型鏈的指向方式。
function Parent () {this.name = 'haha'; }Parent.prototype.getName = function () {console.log(this.name); }function Child () {} Child.prototype = new Parent();var child1 = new Child();console.log(child1.getName()) // haha2、借用構造函數(經典繼承)
function Parent() {this.x = 100;this.y = 199; } Parent.prototype.fn = function() {}function Child() {this.d = 100;Parent.call(this); //構造函數中的this就是當前實例 } var p = new Parent(); var c = new Child(); console.log(p) //Parent {x: 100, y: 199} console.log(c) //Child {d: 100, x: 100, y: 199}優點:通過Funtion的call方法改變this指向,子類繼承了父類的私有屬性和方法,
避免了引用類型的屬性被所有實例共享。還可以在 Child 中向 Parent 傳參,覆蓋父類的私有屬性,如下:
function Parent(z) {this.x = 100;this.y = 199; this.z=z; } Parent.prototype.fn = function() {}function Child(z) {Parent.call(this,z); //構造函數中的this就是當前實例 } var p = new Parent(666); var c = new Child(777); console.log(p) //Parent {x: 100, y: 199, z: 666} console.log(c) //Child {x: 100, y: 199, z: 777}3、組合繼承
結合了原型鏈繼承和構造函數經典繼承,擁有公有和私有的方法屬性。
function Parent (name) {this.name = name;this.colors = ['red', 'blue', 'green']; }Parent.prototype.getName = function () {console.log(this.name) }function Child (name, age) {Parent.call(this, name);//new Child()的時候,調用一次構造函數this.age = age; } //子類的原型指向父類的實例對象 Child.prototype = new Parent(); //這里也調用一次構造函數 //改變子類的原型的constructor屬性為Child,而不是Parent Child.prototype.constructor = Child;var child1 = new Child('Mary', '18');child1.colors.push('black');console.log(child1.name); // Mary console.log(child1.age); // 18 console.log(child1.colors); // ["red", "blue", "green", "black"]優點:融合原型鏈繼承和構造函數的優點,是 JavaScript 中常用的繼承模式。
缺點:每次都會調用兩次構造函數:一次是在創建子類的原型的時候,另一次是在子類型構造函數的內部。子類最終會包含父類型對象的全部實例屬性,但我們不得不在調用子類構造函數時重寫這些屬性。
總結
- 上一篇: 优秀UI设计师需要具备的几个自我修养
- 下一篇: 【JS继承】JS继承之寄生式继承