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');
};

Leave a comment

CandesTheme $75

Advertise / Sponsors

Post a job. Find one. authenticjobs.com How to Be a Rockstar Freelancer
Comments RSS Feed

Recent Comments

  • Oskar Krawczyk: It’s always nice to hear that someone has joined the right side of the force. Have fun!
  • MichaĆ«l Villar: Hi, Great choice. For the home/end key, it’s cmd + left/right arrows. alt + left/right arrows...
  • Astralis: Here’s the fix for the padding issue. Of course, I don’t know what this fix may have broken,...
  • Astralis: The span padding (I believe) in Safari and Chrome don’t work.
  • i8pikachu: This menu doesn’t look so great using Chrome.