Cover by David Flanagan

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Classes and Types

Recall from Chapter 3 that JavaScript defines a small set of types: null, undefined, boolean, number, string, function, and object. The typeof operator (The typeof Operator) allows us to distinguish among these types. Often, however, it is useful to treat each class as its own type and to be able to distinguish objects based on their class. The built-in objects of core JavaScript (and often the host objects of client-side JavaScript) can be distinguished on the basis of their class attribute (The class Attribute) using code like the classof() function of Example 6-4. But when we define our own classes using the techniques shown in this chapter, the instance objects always have a class attribute of “Object”, so the classof() function doesn’t help here.

The subsections that follow explain three techniques for determining the class of an arbitrary object: the instanceof operator, the constructor property, and the name of the constructor function. None of these techniques is entirely satisfactory, however, and the section concludes with a discussion of duck-typing, a programming philosophy that focuses on what an object can do (what methods it has) rather than what its class is.

The instanceof operator

The instanceof operator was described in The instanceof Operator. The left-hand operand should be the object whose class is being tested, and the right-hand operand should be a constructor function that names a class. The expression o instanceof c evaluates to true if ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required