LEARNING JAVASCRIPT - Trang 174

Class and Instance Creation

Prior to ES6, creating a class in JavaScript was a fussy, unintuitive affair. ES6 introdu‐

ces some convenient new syntax for creating classes:

class

Car

{

constructor

() {

}
}

This establishes a new class called

Car

. No instances (specific cars) have been created

yet, but we have the ability to do so now. To create a specific car, we use the

new

keyword:

const

car1

=

new

Car

();

const

car2

=

new

Car

();

We now have two instances of class

Car

. Before we make the

Car

class more sophisti‐

cated, let’s consider the

instanceof

operator, which can tell you if a given object is an

instance of a given class:

car1

instanceof

Car

// true

car1

instanceof

Array

// false

From this we can see that

car1

is an instance of

Car

, not

Array

.

Let’s make the

Car

class a little more interesting. We’ll give it some data (make,

model), and some functionality (shift):

class

Car

{

constructor

(

make

,

model

) {

this

.

make

=

make

;

this

.

model

=

model

;

this

.

userGears

=

[

'P'

,

'N'

,

'R'

,

'D'

];

this

.

userGear

=

this

.

userGears

[

0

];

}

shift

(

gear

) {

if

(

this

.

userGears

.

indexOf

(

gear

)

<

0

)

throw

new

Error(

`Invalid gear:

${

gear

}

`

);

this

.

userGear

=

gear

;

}
}

Here the

this

keyword is used for its intended purpose: to refer to the instance the

method was invoked on. You can think of it as a placeholder: when you’re writing

your class—which is abstract—the

this

keyword is a placeholder for a specific

instance, which will be known by the time the method is invoked. This constructor

allows us to specify the make and model of the car when we create it, and it also sets

up some defaults: the valid gears (

userGears

) and the current gear (

gear

), which we

initialize to the first valid gear. (I chose to call these user gears because if this car has

an automatic transmission, when the car is in drive, there will be an actual mechani‐

150 | 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.