Custom JavaScript Objects

Even though JavaScript is not a pure object-oriented language, it does provide a mechanism for encapsulation. Encapsulation is the ability to package and to hide data in an object. In JavaScript, you can create an instance of a generic object and assign it properties and even methods. For example, in the following JavaScript a generic object instance called cartLineItem is created. The dot operator is used to define and to assign values to four custom properties:

cartLineItem = new Object();
cartLineItem.productID = 'MG1234';
cartLineItem.productName = 'MGB Roadster (1935)';
cartLineItem.qty = 1;
cartLineItem.unitPrice = 36000;

The cartLineItem instance can be used later by any JavaScript with a reference to it. For ...

Get Building Web Applications with UML 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.