Skip to Content
JavaScript: The Good Parts
book

JavaScript: The Good Parts

by Douglas Crockford
May 2008
Intermediate to advanced
172 pages
4h 54m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Good Parts

Reflection

It is easy to inspect an object to determine what properties it has by attempting to retrieve the properties and examining the values obtained. The typeof operator can be very helpful in determining the type of a property:

typeof flight.number      // 'number'
typeof flight.status      // 'string'
typeof flight.arrival     // 'object'
typeof flight.manifest    // 'undefined'

Some care must be taken because any property on the prototype chain can produce a value:

typeof flight.toString    // 'function'
typeof flight.constructor // 'function'

There are two approaches to dealing with these undesired properties. The first is to have your program look for and reject function values. Generally, when you are reflecting, you are interested in data, and so you should be aware that some values could be functions.

The other approach is to use the hasOwnProperty method, which returns true if the object has a particular property. The hasOwnProperty method does not look at the prototype chain:

flight.hasOwnProperty('number')         // true
flight.hasOwnProperty('constructor')    // false
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript for the Impatient

Modern JavaScript for the Impatient

Cay S. Horstmann
Head First JavaScript Programming

Head First JavaScript Programming

Eric T. Freeman, Elisabeth Robson
Learn JavaScript

Learn JavaScript

Shaun Wassell

Publisher Resources

ISBN: 9780596517748Supplemental ContentCatalog PageErrata