日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

JavaScript中的继承

發布時間:2025/7/25 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript中的继承 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在JavaScript中沒有Java中的exends關鍵字,只能通過其他的方式來實現繼承關系。

1) 對象冒充

1 function Parent(username) 2 { 3 this.username = username; 4 5 this.sayHello = function() 6 { 7 alert(this.username); 8 } 9 } 10 11 function Child(username, password) 12 { 13 //下面三行代碼是就是實現了Child繼承Parent的關鍵代碼 14 this.method = Parent; 15 this.method(username); 16 delete this.method; 17 18 this.password = password; 19 20 this.sayWorld = function() 21 { 22 alert(this.password); 23 } 24 } 25 26 var parent = new Parent("zhangsan"); 27 var child = new Child("lisi", "1234"); 28 parent.sayHello(); 29 child.sayHello(); 30 child.sayWorld();

2) call方法方式。
call方法是Function對象中的方法,因此我們定義的每個函數都擁有該方法。可以通過函數名來調用call方法,call方法的第一個參數會被傳遞給函數中的this,從第2個參數開始,逐一賦值給函數中的參數。

1 //使用call方式實現對象的繼承 2 3 function Parent(username) 4 { 5 this.username = username; 6 7 this.sayHello = function() 8 { 9 alert(this.username); 10 } 11 } 12 13 function Child(username, password) 14 { 15 //下面的一行代碼是第一種方式三行關鍵代碼的替換 16 Parent.call(this, username); 17 18 this.password = password; 19 20 this.sayWorld = function() 21 { 22 alert(this.password); 23 } 24 } 25 26 var parent = new Parent("zhangsan"); 27 28 var child = new Child("lisi", "123"); 29 30 parent.sayHello(); 31 32 child.sayHello(); 33 child.sayWorld();

3) apply方法方式

1 //使用apply方法實現對象繼承 2 function Parent(username) 3 { 4 this.username = username; 5 6 this.sayHello = function() 7 { 8 alert(this.username); 9 } 10 } 11 12 function Child(username, password) 13 { 14 Parent.apply(this, new Array(username)); 15 16 this.password = password; 17 18 this.sayWorld = function() 19 { 20 alert(this.password); 21 } 22 } 23 24 var parent = new Parent("zhangsan"); 25 var child = new Child("lisi", "123"); 26 27 parent.sayHello(); 28 29 child.sayHello(); 30 child.sayWorld();

4)原型鏈方式(無法給構造函數傳參數)

1 function Parent() 2 { 3 4 } 5 6 Parent.prototype.hello = "hello"; 7 Parent.prototype.sayHello = function() 8 { 9 alert(this.hello); 10 } 11 12 function Child() 13 { 14 15 } 16 17 Child.prototype = new Parent(); 18 19 Child.prototype.world = "world"; 20 Child.prototype.sayWorld = function() 21 { 22 alert(this.world); 23 } 24 25 var child = new Child(); 26 27 child.sayHello(); 28 child.sayWorld();

5)混合方式(推薦)

1 function Parent(hello) 2 { 3 this.hello = hello; 4 } 5 6 Parent.prototype.sayHello = function() 7 { 8 alert(this.hello); 9 } 10 11 function Child(hello, world) 12 { 13 Parent.call(this, hello); 14 15 this.world = world; 16 } 17 18 Child.prototype = new Parent(); 19 20 Child.prototype.sayWorld = function() 21 { 22 alert(this.world); 23 } 24 25 var child = new Child("hello", "world"); 26 27 child.sayHello(); 28 child.sayWorld();

?

轉載于:https://www.cnblogs.com/daneres/p/4787543.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

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

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