LEARNING JAVASCRIPT - Trang 183

name: Sub
isSuper: true
isSub: true
sneaky: not recommended! (inherited)

The properties

name

,

isSuper

, and

isSub

are all defined on the instance, not in the

prototype chain (note that properties declared in the superclass constructor are

defined on the subclass instance as well). The property

sneaky

, on the other hand,

was manually added to the superclass’s prototype.
You can avoid this issue altogether by using

Object.keys

, which includes only prop‐

erties defined on the prototype.

String Representation

Every object ultimately inherits from

Object

, so the methods available on

Object

are

by default available for all objects. One of those methods is

toString

, whose purpose

is to provide a default string representation of an object. The default behavior of

toString

is to return

"[object Object]"

, which isn’t particularly useful.

Having a

toString

method that says something descriptive about an object can be

useful for debugging, allowing you to get important information about the object at a

glance. For example, we might modify our

Car

class from earlier in this chapter to

have a

toString

method that returns the make, model, and VIN:

class

Car

{

toString

() {

return

`

${

this

.

make

}

${

this

.

model

}

:

${

this

.

vin

}

`

;

}

//...

Now calling

toString

on a

Car

instance gives some identifying information about the

object.

Multiple Inheritance, Mixins, and Interfaces

Some OO languages support something called multiple inheritance, where one class

can have two direct superclasses (as opposed to having a superclass that in turn has a

superclass). Multiple inheritance introduces the risk of collisions. That is, if something

inherits from two parents, and both parents have a

greet

method, which does the

subclass inherit from? Many languages prefer single inheritance to avoid this thorny

problem.
However, when we consider real-world problems, multiple inheritance often makes

sense. For example, cars might inherit from both vehicles and “insurable” (you can

insure a car or a house, but a house is clearly not a vehicle). Languages that don’t sup‐

port multiple inheritance often introduce the concept of an interface to get around

Multiple Inheritance, Mixins, and Interfaces | 159

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.