LEARNING JAVASCRIPT - Trang 180

const

car2

=

new

Car

(

"Mazda"

,

"3"

);

const

car3

=

new

Car

(

"Mazda"

,

"3"

);

car1

.

vin

;

// 0

car2

.

vin

;

// 1

car3

.

vin

// 2

Car

.

areSimilar

(

car1

,

car2

);

// false

Car

.

areSimilar

(

car2

,

car3

);

// true

Car

.

areSame

(

car2

,

car3

);

// false

Car

.

areSame

(

car2

,

car2

);

// true

Inheritance

In understanding the prototype, we’ve already seen an inheritance of a sort: when you

create an instance of a class, it inherits whatever functionality is in the class’s proto‐

type. It doesn’t stop there, though: if a method isn’t found on an object’s prototype, it

checks the prototype’s prototype. In this way, a prototype chain is established. Java‐

Script will walk up the prototype chain until it finds a prototype that satisfies the

request. If it can find no such prototype, it will finally error out.
Where this comes in handy is being able to create class hierarchies. We’ve already dis‐

cussed how a car is generically a type of vehicle. The prototype chain allows us to

assign functionality where it’s most appropriate. For example, a car might have a

method called

deployAirbags

. We could consider this a method of a generic vehicle,

but have you ever been on a boat with an airbag? On the other hand, almost all vehi‐

cles can carry passengers, so a vehicle might have an

addPassenger

method (which

could throw an error if the passenger capacity is exceeded). Let’s see how this scenario

is written in JavaScript:

class

Vehicle

{

constructor

() {

this

.

passengers

=

[];

console

.

log

(

"Vehicle created"

);

}

addPassenger

(

p

) {

this

.

passengers

.

push

(

p

);

}
}

class

Car

extends

Vehicle

{

constructor

() {

super

();

console

.

log

(

"Car created"

);

}

deployAirbags

() {

console

.

log

(

"BWOOSH!"

);

}
}

156 | Chapter 9: Objects and Object-Oriented Programming

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.