1. Computing & Technology

Object Oriented JavaScript

From , former About.com Guide

JavaScript is not really an object oriented language, it is a prototyping language. Apart from the way you define objects though, it works very much like an object oriented language and so many people treat it that way. Whether you actually look at JavaScript as being a prototyping language or an object oriented one the language still makes great use of objects - both those built into the language and those you define for yourself. Before we can use an object approach to writing our JavaScript we must first consider what object based JavaScript actually is and how it will benefit us to use it.

Creating Objects

Object Oriented Features

Working With Objects

  • You can test if a method already exists before adding it.
  • Create your own self property to avoid confusion as to which object "this" refers to.
  • JSON (JavaScript Object Notation) provides an alternative way of creating objects.
  • JavaScript doesn't have namespaces but we can use objects to achieve the same result.
  • Where different versions of code are required by different browsers we can use lazy definition to define just that version that the browser uses.
  • We don't have to copy the existing code if we want to extend the functionality of a method when we copy an object.
  • The usual way of copying an object just provides a reference to the existing object but when we need to we can create a real copy of an object.
  • The way you determine whether something is private to an object in JavaScript is different from the way many other languages do it.
  • With methods you also need to consider how to define them as private or public.
  • By returning the object itself from methods we can set up JavaScript to allow methods to be chained together making complex combinations of method calls possible via a single statement.
  • Strictly speaking all objects in JavaScript are singletons but we still need to cater for where we want all "copies" of an object to actually refer to a single object.

©2012 About.com. All rights reserved.

A part of The New York Times Company.