O'Reilly logo

JavaScript Patterns by Stoyan Stefanov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Object Creation Patterns

Creating objects in JavaScript is easy—you either use the object literal or you use constructor functions. In this chapter we go beyond that and see some additional patterns for object creation.

The JavaScript language is simple and straightforward and often there’s no special syntax for features you may be used to in other languages, such as namespaces, modules, packages, private properties, and static members. This chapter takes you through common patterns to implement, substitute, or just think differently about those features.

We take a look at namespacing, dependency declaration, module pattern, and sandbox patterns—they help you organize and structure your application code and mitigate the effect of the implied globals. Other topics of discussion include private and privileged members, static and private static members, object constants, chaining, and one class-inspired way to define constructors.

Namespace Pattern

Namespaces help reduce the number of globals required by our programs and at the same time also help avoid naming collisions or excessive name prefixing.

JavaScript doesn’t have namespaces built into the language syntax, but this is a feature that is quite easy to achieve. Instead of polluting the global scope with a lot of functions, objects, and other variables, you can create one (and ideally only one) global object for your application or library. Then you can add all the functionality to that object.

Consider the following example: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required