Custom JavaScript Objects

Even though it is not an object-oriented environment, JavaScript does provide a mechanism for encapsulation, or 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. Using the dot operator, four custom properties are defined and assigned values.

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 example, the following ...

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