Js如何實現繼承(js實現繼承的五種方式)

2021-09-10 23:11:24 字數 2658 閱讀 5795

js繼承有5種實現方式:

1、繼承第一種方式:物件冒充

function

parent

(username)

}

function

child

(username,password)

}var parent =

newparent

("zhangsan");

var child =

newchild

("lisi"

,"123456");

parent.

hello()

; child.

hello()

; child.

world()

;

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

call方法是function類中的方法

call方法的第乙個引數的值賦值給類(即方法)**現的this

call方法的第二個引數開始依次賦值給類(即方法)所接受的引數

function

test

(str)

var object =

newobject()

; object.name =

"zhangsan"

; test.

call

(object,

"langsin");

//此時,第乙個引數值object傳遞給了test類(即方法)**現的this,而第二個引數"langsin"則賦值給了test類(即方法)的str

function

parent

(username)

}function

child

(username,password)

}var parent =

newparent

("zhangsan");

var child =

newchild

("lisi"

,"123456");

parent.

hello()

; child.

hello()

; child.

world()

;

function

parent

(username)

}function

child

(username,password)

}var parent =

newparent

("zhangsan");

var child =

newchild

("lisi"

,"123456");

parent.

hello()

; child.

hello()

; child.

world()

;

4、繼承的第四種方式:原型鏈方式,即子類通過prototype將所有在父類中通過prototype追加的屬性和方法都追加到child,從而實現了繼承

function

person()

person.prototype.hello =

"hello"

; person.prototype.

sayhello

=function()

function

child()

child.prototype =

newperson()

;//這行的作用是:將parent中將所有通過prototype追加的屬性和方法都追加到child,從而實現了繼承

child.prototype.world =

"world"

; child.prototype.

sayworld

=function()

var c =

newchild()

; c.

sayhello()

; c.

sayworld()

;

5、繼承的第五種方式:混合方式

混合了call方式、原型鏈方式

function

parent

(hello)

parent.prototype.

sayhello

=function()

function

child

(hello,world)

child.prototype =

newparent()

;//將父類的方法繼承過來

child.prototype.

sayworld

=function()

var c =

newchild

("zhangsan"

,"lisi");

c.sayhello()

; c.

sayworld()

;

js如何實現繼承

js繼承有5種實現方式 1 繼承第一種方式 物件冒充 function parent username function child username,password var parent new parent zhangsan var child new child lisi 123456 pa...

js如何實現繼承

js繼承有5種實現方式 1 繼承第一種方式 物件冒充 function parent username function child username,password var parent new parent zhangsan var child new child lisi 123456 pa...

JS實現繼承

1.使用物件冒充實現繼承 該種實現方式可以實現多繼承 實現原理 讓父類的建構函式成為子類的方法,然後呼叫該子類的方法,通過this關鍵字給所有的屬性和方法賦值 function parent firstname function child firstname var mychild new chi...