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

JavaScript-class.htm

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

Get Programming Atlas 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.