JavaScript OOP Techniques

Posted on July 7th, 2008, by Cristian in Javascript & jQuery

Although JavaScript is classless, we can still create an instantiate objects using a few different techniques. To demonstrate how to construct a JavaScript ‘class’, here are three examples below which are all essentially equivalent.

var test = new App();
var test2 = new App2();
var test3 = new App3();

Function object technique 1, returning an object containing function members.

function App() {
     // Constructor
     return {
          a : function(){
               console.log('a');
          },
          b : function(){
               console.log('b');
          }
     };
};

Function object technique 2, returning an object containing function members.

var App2 = function() {
     // Constructor
     return {
          a : function(){
               console.log('a');
          },
          b : function(){
               console.log('b');
          }
     };
};

Function object technique 3 using prototyping.

var App3 = function() {
     // Constructor
};

App3.prototype.a = function() {
     console.log('a');
};

App3.prototype.b = function() {
     console.log('b');
};

One comment

  1. Ionut Popa on April 14th, 2009 at 3:03 pm

Leave a comment

Advertise / Sponsors

Comments RSS Feed

Recent Comments

  • Alex: try this: #style { -webkit-width:900px; } worked for me
  • Cristian: I am not modifying the core files. What I post as example is part from a module that observer an event and...
  • Magnus_A: Great idea. I am searching for a payment option that will allow me to add a handling fee to the order. In...
  • Cristian: Yes, is tru the plugin doesn’t support that. But also I think that you are able to control level 2...
  • donny: Hi Christian, thanks but what i miss a sub menu unter a submenu. I have a horizontal structure with 5 op...