DIV CSS 佈局教程網

JavaScript 實現繼承的五種方式詳解
編輯:關於JavaScript     

本文系統講解 JavaScript 實現繼承的五種方式,供感興趣的朋友參考。

1、第一種:對象冒充

 function Parent(username){ this.username = username; this.hello = function(){ alert(this.username); } } function Child(username,password){ //通過以下3行實現將Parent的屬性和方法追加到Child中,從而實現繼承 //第一步:this.method是作為一個臨時的屬性,並且指向Parent所指向的對象, //第二步:執行this.method方法,即執行Parent所指向的對象函數 //第三步:銷毀this.method屬性,即此時Child就已經擁有了Parent的所有屬性和方法 this.method = Parent; this.method(username);//最關鍵的一行 delete this.method; 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(); 

2、第二種:call() 方法方式

call 是 Function 類中的方法:第一個參數會賦值給方法內部出現的 this,從第二個參數起依次賦值給方法接收的參數。

 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(); 

3、第三種:apply() 方法方式

apply 接收兩個參數:第一個與 call 相同,賦值給方法內部的 this;第二個是數組類型,數組中每個元素依次賦值給方法接收的參數。

 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(); 

4、第四種:原型鏈方式,即子類通過 prototype 把父類原型上的屬性與方法都追加過來,從而實現繼承。

 function Person(){ } Person.prototype.hello = "hello"; Person.prototype.sayHello = function(){ alert(this.hello); } function Child(){ } Child.prototype = new Person();//這行的作用是:將Parent中將所有通過prototype追加的屬性和方法都追加到Child,從而實現了繼承 Child.prototype.world = "world"; Child.prototype.sayWorld = function(){ alert(this.world); } var c = new Child(); c.sayHello(); c.sayWorld(); 

5、第五種:混合方式

融合了 call 方式與原型鏈方式。

 function Parent(hello){ this.hello = hello; } Parent.prototype.sayHello = function(){ alert(this.hello); } function Child(hello,world){ Parent.call(this,hello);//將父類的屬性繼承過來 this.world = world;//新增一些屬性 } Child.prototype = new Parent();//將父類的方法繼承過來 Child.prototype.sayWorld = function(){//新增一些方法 alert(this.world); } var c = new Child("zhangsan","lisi"); c.sayHello(); c.sayWorld(); 

希望本文所述對你的 JavaScript 學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved