LEARNING JAVASCRIPT - Trang 185

Now it’s as if our methods have always been part of class

Car

. And, from JavaScript’s

perspective, they are. From the development perspective, we’ve made it easier to

maintain these two important classes. The automotive engineering group manages

and develops the

Car

class, and the insurance group manages the

InsurancePolicy

class and the

makeInsurable

mixin. Granted, there’s still room for the two groups to

interfere with each other, but it’s better than having everyone working on one giant

Car

class.

Mixins don’t eliminate the problem of collisions: if the insurance group were to create

a method called

shift

in their mixin for some reason, it would break

Car

. Also, we

can’t use

instanceof

to identify objects that are insurable: the best we can do is duck

typing (if it has a method called

addInsurancePolicy

, it must be insurable).

We can ameliorate some of these problems with symbols. Let’s say the insurance

group is constantly adding very generic methods that are inadvertently trampling

Car

methods. You could ask them to use symbols for all of their keys. Their mixin would

then look like this:

class

InsurancePolicy

() {}

const

ADD_POLICY

=

Symbol

();

const

GET_POLICY

=

Symbol

();

const

IS_INSURED

=

Symbol

();

const

_POLICY

=

Symbol

();

function

makeInsurable

(

o

) {

o

[

ADD_POLICY

]

=

function

(

p

) {

this

[

_POLICY

]

=

p

; }

o

[

GET_POLICY

]

=

function

() {

return

this

[

_POLICY

]; }

o

[

IS_INSURED

]

=

function

() {

return

!!

this

[

_POLICY

]; }

}

Because symbols are unique, this ensures that the mixin will never interfere with

existing

Car

functionality. It makes it a little more awkward to use, but it’s much safer.

A middle-ground approach might have been to use regular strings for methods, but

symbols (such as

_POLICY

) for data properties.

Conclusion

Object-oriented programming is a tremendously popular paradigm, and for good

reason. For many real-world problems, it encourages organization and encapsulation

of code in a way that makes it easy to maintain, debug, and fix. JavaScript’s implemen‐

tation of OOP has many critics—some even go so far as to say that it doesn’t even

meet the definition of an OO language (usually because of the lack of data access con‐

trols). There is some merit to that argument, but once you get accustomed to JavaS‐

cript’s take on OOP, you’ll find it’s actually quite flexible and powerful. And it allows

you to do things that other OO languages would balk at.

Conclusion | 161

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.