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
- Built in objects that can be used without needing to create them
- How to extend built in objects to add extra functionality.
- You can create a new object by copying and extending an existing one.
- You can also create a new object from scratch.
Object Oriented Features
- The easiest way to tell if code is object oriented is if it uses dot notation or the "this" keyword.
- The prototype property provides access to the parent object allowing methods to be shared.
- Objects can inherit from other objects through the constructor property.
- As well as dot notation, JavaScript also supports associative array notation for accessing properties.
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.
