Revision [15287]

This is an old revision of WritingObjectOrientedJavaScript made by AbydonianSoftware on 2013-07-25 09:49:23.


Writing Object Oriented JavaScript

Object Oriented JavaScript is a great way to organize your JavaScript source code, so that it is portable, readable, maintainable and encapsulated. This method of JavaScript development is a sort of self-imposed discipline, that makes JavaScript far more organized than it often is in web applications.

Object Oriented JavaScript Using Prototypes

In this example, we are going to show how to create a basic JavaScript module using prototypes.

The Constructor
The Constructor looks just like a function call, in this method of JavaScript coding. In the constructor, we can save any parameters we want to pass in, into the object's local variables and possibly kick off any initialization processes.

function DataEditor(imagePath) {
    this.imagePath = imagePath; // save imagePath to a local variable, inside of DataEditor

Member Functions
Member functions provide all of the functionality and are encapsulated in the object, meaning that you must instantiate the object and reference all functions from an instance of the object, in order to use the member functions. These member functions will have access to all variables encapsulated in the object.

Here is a simple example, where we define a function called init. Note that unlike typical JavaScript functions, we create a prototype attribute and then make that attribute equal to the function. Syntax errors in this very basic structure can be tricky to diagnose, if you're not accustomed to using this style of coding.

DataEditor.prototype.init=function() {

Valid XHTML :: Valid CSS: :: Powered by WikkaWiki