js之旅(九)js的繼承

2021-10-07 18:54:26 字數 3266 閱讀 5371

本文主要講解js中幾種實現繼承的方法。

通過【某種方式】讓乙個物件可以訪問到另乙個物件中的屬性和方法,我們把這種方式稱之為繼承 並不是所謂的*** extends yyy

這裡構造乙個父建構函式animal()

function

animal

(age, name)

}//原型方法

animal.prototype.

sleep

=function()

//原型屬性

animal.prototype.type =

"animal"

;

原型繼承就是將子建構函式的例項原型指向父建構函式的例項原型,即子建構函式.prototype = 父建構函式.prototype,思考一下,這樣的做法的特點:

function

dog(

)dog.prototype = animal.prototype;

//自定義原型物件時,盡量重寫constructor再指向該函式

dog.prototype.constructor = dog;

var dog1 =

newdog()

;dog1.

say();

is not a function

dog1.

sleep()

;//undefined is sleeping

var dog2 =

newdog()

;dog2.__proto__.type =

"dog"

;console.

log(dog1.type)

;//dog

原型鏈繼承實際是就是將子建構函式的例項原型指向父建構函式的例項:子建構函式.prototype = new 父建構函式(),思考一下該繼承的特點:

function

dog(name)

dog.prototype =

newanimal(6

,"animal");

var dog1 =

newdog

("dog1");

var dog2 =

newdog

("dog2");

console.

log(dog1.age)

;//6

dog1.

say();

//i am dog1, and 6 years old

console.

log(dog1.type)

;//animal

dog1.

sleep()

;//dog1 is sleeping

dog2.friend.

push

("dog1");

console.

log(dog1.friend)

;//["dog1"]

function

dog(arg)

var dog1 =

newdog([

6,"dog1"])

;var dog2 =

newdog([

7,"dog2"])

;dog1.

say();

//i am dog1, and 6 years old

dog2.

say();

//i am dog2, and 7 years old

dog1.

sleep()

; uncaught typeerror: dog1.sleep is not a function

組合繼承就是建構函式繼承 + 原型鏈繼承,思考這種繼承方式的特點:

function

dog(arg)

dog.prototype =

newanimal()

;var dog1 =

newdog([

6,"dog1"])

;var dog2 =

newdog([

7,"dog2"])

;dog1.

say();

//i am dog1, and 6 years old

dog2.

say();

//i am dog2, and 7 years old

dog1.

sleep()

;//dog1 is sleeping

dog2.

sleep()

;//dog2 is sleeping

dog1.__proto__.type =

"dog1"

;console.

log(dog2.__proto__.type)

;//dog1

通過寄生方式,砍掉父類的例項屬性,這樣,在呼叫兩次父類的構造的時候,就不會初始化兩次例項方法/屬性,避免的組合繼承的缺點。本質上就是對組合繼承的優化,可以理解為:建構函式繼承 + 僅僅繼承父原型例項的原型鏈繼承,它兼有組合繼承的優點,同時修復了它的缺點,特點如下:

function

dog(arg)

dog.prototype = object.

create

(animal.prototype)

;dog.prototype.constructor = dog;

var dog1 =

newdog([

6,"dog1"])

;var dog2 =

newdog([

7,"dog2"])

;dog1.

say();

//i am dog1, and 6 years old

dog2.

say();

//i am dog2, and 7 years old

dog1.

sleep()

;//dog1 is sleeping

dog2.

sleep()

;//dog2 is sleeping

dog1.__proto__.type =

"dog1"

;console.

log(dog2.__proto__.type)

;//dog1

js之旅(七)js中this

本文講述js中this的指向 介紹es5和es6中this的不同 在js es5中,使用的是function函式,誰在呼叫function,this就指向誰,有以下幾個特點 1.1 this最終指向的是呼叫它的物件 這個特點的就是es5中this的指向,其它特點都是對它的補充,如下示例 functi...

js之旅(六)js中set的使用

set是es6中的資料結構,和陣列的區別是set不能有重複的值,本文將簡單介紹set的使用。js中使用new set 來宣告set var a newset v1 console.log a set 1 a.add v2 console.log a set 2 console.log typeof ...

js繼承 來自js高階

繼承 組合繼承 原型繼承與借用建構函式 用建構函式實現對例項屬性的繼承,用原型鏈實現對原型屬性和方法的繼承 function super name super.prototype.sayname function function sub name,age sub.prototype new sup...