JavaScript繼承概念:js是基於對象的,他沒有類的概念,所以實現繼承,需要使用js的原型prototype機制或者用applay和call方法實現。
1、原型鏈繼承:
即子類通過prototype將所有在父類中通過prototype追加的屬性和方法都追加到Child,從而實現了繼承
為了讓子類繼承父類的屬性(也包括方法),首先需要定義一個構造函數。然后,將父類的新實例賦值給構造函數的原型。
function parent(){ this.name="garuda"; } function child(){ this.sex="man" } child.prototype=new parent();//核心:子類繼承父類,通過原型形成鏈條 var test=new child(); console.log(test.name); console.log(test.sex);
備注:在js中,被繼承的函數稱為超類型(父類、基類),繼承的函數稱為子類型(子類、派生類)。
使用原型繼承存在兩個問題:一是面量重寫原型會中斷關系,使用引用類型的原型,二是子類型還無法給超類型傳遞參數
電腦刺綉綉花廠 http://www.szhdn.com 廣州品牌設計公司https://www.houdianzi.com
2、借用構造函數繼承
function parent(){ this.name="garuda"; } function child(){ parent.call(this);//核心:借父類型構造函數增強子類型(傳參) } var test =new parent(); console.log(test.name);
3、call()方法方式
call方法是Function類中的方法
call方法的第一個參數的值賦值給類(即方法)中出現的this
call方法的第二個參數開始依次賦值給類(即方法)所接受的參數
function test(str){ alert(this.name + " " + str); } var object = new Object(); object.name = "zhangsan"; test.call(object,"langsin");//此時,第一個參數值object傳遞給了test類(即方法)中出現的this,而第二個參數"langsin"則賦值給了test類(即方法)的str function Parent(username){ this.username = username; this.hello = function(){ alert(this.username); } } function Child(username,password){ Parent.call(this,username); this.password = password; this.world = function(){ alert(this.password); } } var parent = new Parent("zhangsan"); var child = new Child("lisi","123456"); parent.hello(); child.hello(); child.world();
4、apply()方法方式
apply方法接受2個參數,
A、第一個參數與call方法的第一個參數一樣,即賦值給類(即方法)中出現的this
B、第二個參數為數組類型,這個數組中的每個元素依次賦值給類(即方法)所接受的參數
function Parent(username){ this.username = username; this.hello = function(){ alert(this.username); } } function Child(username,password){ Parent.apply(this,new Array(username)); this.password = password; this.world = function(){ alert(this.password); } } var parent = new Parent("zhangsan"); var child = new Child("lisi","123456"); parent.hello(); child.hello(); child.world();
5、組合繼承(原型鏈和構造函數組合)
function parent(){ this.name="garuda"; } function borther(){ return this.name; } function child(){ parent.call(this) } child.prototype=new parent(); var test=new parent(); console.log(test.borther())