Object-Oriented Programming (OOP)

JavaScript is a so-called object-based language, but not an object-oriented one. There are aspects of JavaScript that are OOP-like, but support for 33onventional OOP techniques is limited. For instance, visibility of class members (public, private, protected, etc.) can be implemented only in a limited way. Nevertheless, it is possible to create classes in JavaScript and even to provide rudimentary support for class inheritance.

A class in JavaScript is implemented by creating a function. The code within this function is the class constructor and getter and setter methods for the class properties, which are also defined in the constructor. All class properties and methods are defined within the class code. The this keyword provides access to the properties of the current class, making it possible to set properties and define methods.

Example 2-9 shows a simple class that implements a book. Note that access to the class’s properties is via explicit getter and setter methods instead of the more familiar dot notation (such as book.title).

Example 2-9. Using JavaScript’s OOP features


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml">
  <script language="JavaScript" type="text/javascript">
  function Book(isbn, author, title) { var _isbn = isbn; var _author = author; ...

Get Programming Atlas now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.