JS實現繼承的方法

2021-09-02 00:24:49 字數 2191 閱讀 5664

一、物件冒充:

function

parent

(username)

}function

child

(username,password)

}var parent =

newparent

("liuxiaowei");

var child =

newchild

("admin"

,"123456");

parent.

hello()

;//liuxiaowei

child.

hello()

;//admin

child.

world()

;//123456

二、call方式:

call()是function類中的方法

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

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

function

parent

(username)

}function

child

(username,password)

}var parent =

newparent

("liuxiaowei");

var child =

newchild

("admin"

,"123456");

parent.

hello()

;//liuxiaowei

child.

hello()

;//admin

child.

world()

;//123456

缺點:

1.例項不是父類的例項,只是子類的

2.只能繼承父類的屬性和方法,不能繼承父類原型屬性和方法

3.無法實現函式服用,每個子類都有父類例項函式的副本

parent.

(this

,new

array

(username)

);

四、原型鏈方式
function

parent()

parent.prototype.hello =

"hello"

;parent.prototype.

sayhello

=function()

function

child()

child.prototype =

newperson()

;//將parent中所有通過prototype追加的屬性和方法都追加到child

child.prototype.world =

"world"

;child.prototype.

sayworld

=function()

var c =

newchild()

;c.sayhello()

;//hello

c.sayworld

(); //world

缺點:

1.無法多繼承

2.來自原型物件的所有屬性被所有例項共享

3.建立子類例項時,無法向父建構函式傳參

五、call、原型鏈混合方式

function

parent

(hello)

parent.prototype.

sayhello

=function()

function

child

(hello,world)

child.prototype =

newparent()

;child.prototype.

sayworld

=function()

var c =

newchild

("admin"

,"123456");

c.sayhello()

;//admin

c.sayworld()

;//123456

缺點:

1.呼叫了兩次父類建構函式,生成了兩份例項(子類例項將子類原型上那份遮蔽了)

js的繼承實現方法

一 原型鏈 利用prototype實現繼承,prototype物件是個模板,要例項的物件都是以這個模板為基礎,它的任何屬性和方法都被傳遞給那個類的所有例項,原型鏈利用這種功能來實現繼承機制。如果利用原型方式實現繼承,例項如下 原型鏈function classa classa.prototype.c...

JS實現繼承的常用方法

1 建構函式繼承 function parent name parent.prototype.saihi function function child name,age,gender let child new child 王磊 20,男 console.log child.name 王磊 chi...

JS實現繼承的幾種方法

call方法的第乙個引數的值賦值給類 即方法 中出現的 this call方法的第二個引數開始依次賦值給類 即方法 所接受的引數 call 相同,第二個引數為陣列型別,這個陣列中的每個元素依次賦值給類 即方法 所接受的引數 this 的指向,我們就是利用它的這個特性來實現繼承的。補充知識點 func...