日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JS继承的应用案例

發布時間:2023/12/29 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()) // haha

2、借用構造函數(經典繼承)

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 中常用的繼承模式。

缺點:每次都會調用兩次構造函數:一次是在創建子類的原型的時候,另一次是在子類型構造函數的內部。子類最終會包含父類型對象的全部實例屬性,但我們不得不在調用子類構造函數時重寫這些屬性。

總結

以上是生活随笔為你收集整理的JS继承的应用案例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。