LEARNING JAVASCRIPT - Trang 177

intuitive and straightforward, under the hood the nature of classes in JavaScript hasn’t

changed (

class

just adds some syntactic sugar), so it’s important to understand how a

class is represented in JavaScript.
A class is really just a function. In ES5, we would have started our

Car

class like this:

function

Car

(

make

,

model

) {

this

.

make

=

make

;

this

.

model

=

model

;

this

.

_userGears

=

[

'P'

,

'N'

,

'R'

,

'D'

];

this

.

_userGear

=

this

.

userGears

[

0

];

}

We can still do this in ES6: the outcome is exactly the same (we’ll get to methods in a

bit). We can verify that by trying it both ways:

class

Es6Car

{}

// we'll omit the constructor for brevity

function

Es5Car

{}

>

typeof

Es6Car

// "function"

>

typeof

Es5Car

// "function"

So nothing’s really new in ES6; we just have some handy new syntax.

The Prototype

When you refer to methods that are available on instances of a class, you are referring

to prototype methods. For example, when talking about the

shift

method that’s avail‐

able on

Car

instances, you’re referring to a prototype method, and you will often see

it written

Car.prototype.shift

. (Similarly, the

forEach

function of

Array

would be

written

Array.prototype.forEach

.) Now it’s time to actually learn what the proto‐

type is, and how JavaScript performs dynamic dispatch using the prototype chain.

Using a number sign (#) has emerged as a popular convention for

describing prototype methods. For example, you will often see
Car.prototype.shift

written simply as Car#shift.

Every function has a special property called

prototype

. (You can vary this for any

function

f

by typing

f.prototype

at the console.) For regular functions, the proto‐

type isn’t used, but it’s critically important for functions that act as object construc‐

tors.

By convention, object constructors (aka classes) are always named

with a capital letter—for example, Car. This convention is not

enforced in any way, but many linters will warn you if you try to

name a function with a capital letter, or an object constructor with

a lowercase letter.

Object-Oriented Programming | 153

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.