Skip to Content
Programming JavaScript Applications
book

Programming JavaScript Applications

by Eric Elliott
June 2014
Intermediate to advanced
254 pages
6h 2m
English
O'Reilly Media, Inc.
Content preview from Programming JavaScript Applications

Chapter 3. Objects

With the combination of prototypal inheritance, dynamic object extension, and closures, JavaScript has one of the most flexible and expressive object systems available in any popular programing language.

In JavaScript, all types of functions, arrays, key/value pairs, and data structures in general are really objects. Even primitive types get the object treatment when you refer to them with the property access notations. They get automatically wrapped with an object so that you can call their prototype methods. For example:

'tonya@example.com'.split('@')[1]; // => example.com

Caution

Primitive types behave like objects when you use the property access notations, but you can’t assign new properties to them. Primitives get wrapped with an object temporarily, and then that object is immediately thrown away. Any attempt to assign values to properties will seem to succeed, but subsequent attempts to access that new property will fail.

JavaScript’s object system is so powerful and expressive that most of the complexity in common OO patterns melts away when you reproduce them in JavaScript. You simply don’t need all of the common cruft to accomplish the stated goals. For instance, because JavaScript is classless, and it’s possible to create an object on demand at the precise moment it’s needed (lazy instantiation), the singleton is reduced to an object literal:

var highlander = {
    name: 'McLeod',
    catchphrase: 'There can be only one.'
  };

As you continue through this chapter, you’ll ...

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

JavaScript : Object-Oriented Programming

JavaScript : Object-Oriented Programming

Kumar Chetan Sharma et al
Testing JavaScript Applications

Testing JavaScript Applications

Lucas Fernandes da Costa

Publisher Resources

ISBN: 9781491950289Errata PageSupplemental Content