借用構造函式呼叫繼承

2021-08-30 11:35:14 字數 1505 閱讀 7330

function

father

(name,age)

//這樣直接呼叫,那麼father中的this只的是 window。 因為其實這樣呼叫的: window.father("李四", 20)

// name 和age 屬性就新增到了window屬性上

father

("李四",20

);alert

("name:"

+ window.name +

"\nage:"

+ window.age)

;//使用call方法呼叫,則可以改變this的指向

function

son(name, age, ***)

var son =

newson

("張三",30

,"男");

alert

("name:"

+ son.name +

"\nage:"

+ son.age +

"\n***:"

+ son.***)

;alert

(son instanceof

father);

//false

函式借調的方式還有別的實現方式,但是原理都是一樣的。

但是有一點要記住,

這裡其實並沒有真的繼承,僅僅是呼叫了father建構函式而已。也就是說,son物件和father沒有任何的關係。

3.2借用的缺陷

father的原型物件中的共享屬性和方法,son沒有辦法獲取。因為這個根本就不是真正的繼承。

四、組合繼承

​ 組合函式利用了原型繼承和建構函式借調繼承的優點,組合在一起。成為了使用最廣泛的一種繼承方式。

//定義父型別的建構函式

function

father

(name,age)}}

// 定義子類型別的建構函式

function

son(name, age, ***)

//修改子型別的原型。這樣就可以繼承父型別中的方法了。

son.prototype =

newfather()

;var son1 =

newson

("志玲",30

,"女");

alert

(son1.name)

;alert

(son1.***)

;alert

(son1.age)

; son1.

eat();

組合繼承是我們實際使用中最常用的一種繼承方式。

可能有個地方有些人會有疑問:son.prototype =

newfather()

;這不照樣把父型別的屬性給放在子型別的原型中了嗎,還是會有共享問題呀。但是不要忘記了,我們在子型別的建構函式中借調了父型別的建構函式,也就是說,子型別的原型中有的屬性,都會被子類物件中的屬性給覆蓋掉。就是這樣的。

借用建構函式實現繼承

在子型別建構函式的內部呼叫超型別的建構函式 function supertype function subtype var instance1 new subtype instance1.colors.push yellow console.log instance1.colors var inst...

繼承方式二 借用建構函式

function supertype function subtype var instance1 newsubtype instance1.colors.push black console.log instance1.colors red blue green black var instanc...

物件導向(繼承) 借用建構函式02

首先回顧一下原型鏈中引用型別值帶來的問題 function supertype function subtype 繼承了 supertype subtype.prototype new supertype var instance1 new subtype instance1.colors.push...