Chapter 6. Object-Oriented Programming

Object-oriented (OO) languages typically are identified through their use of classes to create multiple objects that have the same properties and methods. As mentioned previously, ECMAScript has no concept of classes, and therefore objects are different than in class-based languages.

ECMA-262 defines an object as an "unordered collection of properties each of which contains a primitive value, object, or function." Strictly speaking, this means that an object is an array of values in no particular order. Each property or method is identified by a name that is mapped to a value. For this reason (and others yet to be discussed), it helps to think of ECMAScript objects as hash tables: nothing more than a grouping of name-value pairs where the value may be data or a function.

Each object is created based on a reference type, either one of the native types discussed in the previous chapter or a developer-defined type.

Creating Objects

As mentioned in the previous chapter, the simplest way to create a custom object is to create a new instance of Object and add properties and methods to it, as in this example:

var person = new Object(); = "Nicholas";
person.age = 29;
person.job = "Software Engineer";

person.sayName = function(){

This example creates an object called person that has three properties (name, age, and job) and one method (sayName()). The sayName() method displays the value of, which resolves to

Get Professional, JavaScript® for Web Developers, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.