Quick JavaScript OO (Object Orientation) Primer

by on December 20, 2012 11:23 am

Recently I’ve been working heavily with JavaScript to implement full-blown rich user interfaces for web-based applications. In the past, I’ve used JavaScript and supporting libraries, such as JQuery and Jquery UI to introduce cool UI widgets to enhance my server side Java web applications.

But, as I’ve been introducing the MVC pattern to the browser using supporting JavaScript libraries, I’ve had to learn how to write object oriented modular JavaScript. And yes, you can do object oriented programming with JavaScript. So, I’d like to introduce some basic object oriented JavaScript concepts.

Initializer Objects

JavaScript is dynamic, meaning that when you define things such as function, expressions, or variables — they are defined. There’s not a compilation process to check syntax or typing (as there is in typed languages such as Java or C#). Object definitions are also dynamic and are simply an unordered collection of key/value pairs.

Here’s an expression that defines a JavaScript object:

var object = {};    // object created

This is referred to as a Initializer object, and it has no state or methods to execute. Since JavaScript is dynamic, properties can be added at any time. Age and name properties are added with the expressions below:

object.age = 49;
object.name = “Clifford”;
alert(object.age +”:”+ object.name); // shows 49 : Clifford


Functions are also objects, and are used to create methods. Essentially, a function object is defined and assigned to an object property. The expressions below defines a print function, and assigns and executes the method:

// print() method
object.print =  function() {  return object.age +”:”+ object.name;    };
// execute method
console.log(object.print());  // shows 49: Clifford

Using JSON Type Syntax

A complete object can be defined using JSON type syntax. Here’s an example of how a “person” object can be created in a single expression:

var person  = { name: "david",
age: 40,
print: function() { return name + ":"+age}};
console.log(person.print());   // shows david:40

Personally, my object oriented programming background comes from Smalltalk — dating myself — with the last decade using Java and C#. I’ve come to find out that the JavaScript community refers to this as a classical way of OO thinking. In the next section, I’ll introduce another way to define JavaScript objects, commonly referred to as the “classical” object approach.

Constructor Objects

Objects may also be defined so that they are created using the classical “new” operator, along with specifying initialization parameters. Any function that is assigned to a variable can be issued the new command, and an object will be created.

The example below shows how a constructor function is defined, and how it accepts name and age values that are assigned to the “Person” variable:

var Person = new function(name,age) {
    this.name = name;
    this.age = age;
    this.print = function() {
        return his.age +”:”+ this.name;

An object can be created and used, as long as the “person” variable is in scope with the expressions below:

var person = new Person(“Clifford”,49);

Object Prototypes

As you can see, JavaScript does not have classes as with other classical OO languages such as Java or C#. Instances are created using prototypes, and as such, all constructor object references have a prototype property reference that can be used to extend object implementations.

Consider the String global object reference. Its prototype reference can be used to extend its functionality with a repeat method as in the expressions below:

String.prototype.repeat = function(x) {
    return count >  1 ?  '' : new Arrray(count + 1).join(this);

Once extended, it can be used as followed:

“Hello”.repeat(3);      // returns “HelloHelloHello”;

Emulating Inheritance

JavaScript does not have an inheritance mechanism, but by using prototypes you may emulate it.

The example below defines two objects: Person and User. The User constructor object defines two attributes but inherits properties and methods from the “Person” object by assigning its prototype. Here is JavaScript carrying this out:

// Person Object
var Person = function() {
    this.print = function() {
        return "Age:"+this.age+" - "+"Name: "+this.name;
// User Object
var User = function() {
// Create User that extends/inherits from Person
function createUser() {
    // inherit
    User.prototype = new Person();
    // create instance
    var user = new User();
    // add user properties
    return user;

Usage of the user object is shown below:

var u = createUser();
// inherited print() method..
alert(u.print() + "id:"+u.id + "password:"+u.password);

Emulating inheritance using initializer objects can be implemented by defining a method on a base object that dynamically copies properties/methods to a supplied object. This technique is done in the backbone.js framework to allow the base view object to be extended with sub-objects.

Here’s how a extend() method can be implemented in the previous example:

// Function to extend Person object
function extend(object) {
    var base = new Person();
    for (var attr in base) {
        object[attr] = base[attr];
    return object;

An object that extends a “Person” object definition can be done with this expression:

var user = extend({id:"abcd",password:"123"});
// Person print() method inherited
alert(user.print() + "id:"+user.id + "password:"+user.password);

Super is a reserved word in JavaScript, however it is not implemented. You’ll have to roll your own implementation for accessing parent objects in an inheritance chain.

I have shown you a very basic way to implement inheritance, but there are more nuances (such as overriding and super mechanism) that have to be considered. But hopefully this provides some context.


Yes, JavaScript provides support for formal getter/setters. This was a late addition, but I am pretty sure all newer browsers support getter/setters. They mirror the C# implementation, as in Java you still have to implement them.

I really like the way the getter/setter code blocks are hidden. Here is how you would apply them to the name attribute of the example object that we’ve been working with:

// Person Object
var Person = function() {
    var name;
    this.print = function() {
        return "Age:"+this.age+" - "+"Name: "+this.name;
    // getter/setters
    this.__defineGetter__("name", function(){
        return value;
    this.__defineSetter__("name", function(val){
        value = val;

Getter/Setter methods are invoked just like attributes. Here’s an example:

Person person = new Person();
// setter executed
person.name = “Chris”;
// getter exectued
person.name;   // shows “Chris”;


If you are new to applying JavaScript as a general purpose programming language, then these basic object constructs should help you as you progress in applying modularity frameworks (such as require.js or backbone.js) and writing general purpose applications with JavaScript. Good luck!

– David Pitt, asktheteam@keyholesoftware.com

  • Share:

7 Responses to “Quick JavaScript OO (Object Orientation) Primer”

  1. Lou Mauget says:

    David, I just happen to be working in this area. This blog is good enough to for me use as a cheat sheet for these concepts.

  2. David says:

    Thanks Lou, you’re a “classical” man :)

  3. Dawesi says:

    Great intro for nubes. Some notes:

    1) As best practice you should never extend base lang functions (string, function, array, etc) as they could cause collisions with other code. If you want to extend these you should create your own lang functions. (ie: String.prototype.repeat could be MyString.prototype.repeat)

    2) using new keyword for function is redundant (ie: var Person = new function(name,age) ) you should use var Person = function(name,age) and only use new on the new instance.

    3) Most MVC javascript apps have one ‘class’ per file. Sencha MVC is a great example of this, and other frameworks are now using this best practise also.

    4) javascript doesn’t emulate inheritance. It uses prototypal inheritance instead of classical inheritance

    5) __defineGetter__ and __defineSetter__ are depreciated. They don’t work cross browser anymore. In your example they are redudant anyway. Frameworks like ExtJS allow you getters and setters out of the box (run it through sencha cmd and it’s one of the lightest frameworks out there)

    Great article, with a couple of tweaks is a great intro. Well done!

  4. David says:

    Thanks for the info and clarifications and suggestions…David

  5. [...] these sorts of things can be done in JavaScript’s prototypical system (see David Pitt’s blog post on the subject), but it tends to be more verbose, a bit confusing and far from elegant. In fact, it [...]

  6. [...] these sorts of things can be done in JavaScript’s prototypical system (see David Pitt’s blog post on the subject), but it tends to be more verbose, a bit confusing and far from elegant. In fact, it [...]

  7. Howdy! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the great work!

Leave a Reply

Things Twitter is Talking About
  • code smell: dev practices that leave a stench of inexperience. Avoid it in method implementation with these tips - http://t.co/b7A884BnXb
    April 23, 2014 at 9:20 PM
  • Tech Night is now! Mark D is presenting to the group on #Grunt 101. Good technology talk, food & team makes for a fantastic night.
    April 23, 2014 at 5:10 PM
  • Single Page Application architectures allow for rich, responsive UIs. #JavaScript is a must-know for SPA - http://t.co/6sfk3kt1k3 #tutorial
    April 23, 2014 at 2:15 PM
  • Vacuole #Encapsulation aims to minimize the code necessary for routinely verbose data tasks -http://t.co/fJQzz731rZ
    April 23, 2014 at 9:45 AM
  • DYK? We translate our hands-on experience to custom courses to train your dev teams. Our new course on #AngularJS: http://t.co/Bf3UuClj4Z
    April 23, 2014 at 8:45 AM
  • Interested in #Backbone & #Marionette but not sure where to start? Check out the Marionette-Require-Boilerplate: http://t.co/XDj43BwSS3 #SPA
    April 22, 2014 at 4:50 PM
  • Responsive Design can help in giving your users a consistent app experience across devices. Quick tutorial - http://t.co/BDrT5LvgRo
    April 22, 2014 at 2:31 PM
  • Tips & tricks to save time in the #Eclipse IDE - http://t.co/uGgCkchwNk (keystroke combos, navigation, time tracking & more)
    April 22, 2014 at 8:40 AM
  • Join us! Looking to add to our team a developer w/ advanced #JavaScript & #NodeJS exp (& love of tech variety). Info: http://t.co/cC9CU1RCF9
    April 21, 2014 at 7:35 PM
  • Looking into #ExtJS but don't know where to start? Check out our video tutorial series to find your way around - http://t.co/XFYDT6YNWA
    April 21, 2014 at 4:35 PM
  • We've been tinkering with JS library Famo.us since its public release 4/10. What we've learned so far via a POC app - http://t.co/S77TSKHDKd
    April 21, 2014 at 2:03 PM
  • RT @CompSciFact: Rivest, Shamir, and Adleman published the RSA public key cryptography algorithm in 1978.
    April 21, 2014 at 11:13 AM
  • DYK? When we share/RT/blog/etc, it doesn't mean that Keyhole endorses it - we just like variety of opinions! Info: http://t.co/MXhB9lE9tV
    April 19, 2014 at 3:01 PM
  • A huge welcome to Justin Graber who joined the Keyhole team this week!
    April 18, 2014 at 3:25 PM
  • Pssst... @kc_dc early bird pricing ends on Sunday. Shoot us a note if you want to save 10% off of your ticket with our sponsor promo code!
    April 18, 2014 at 2:49 PM
  • Join our team! Looking for a developer w/ advanced #JavaScript & #NodeJS experience (& love of tech variety). Info: http://t.co/cC9CU1RCF9
    April 18, 2014 at 11:21 AM
  • .@befamous has huge potential to make HTML5/JS/CSS web pages feel as native apps. Here's our inital tech takeaways - http://t.co/S77TSKHDKd
    April 18, 2014 at 9:50 AM
  • Why to use AngularUI Router instead of ngRoute - http://t.co/tBnj5ZCkOw
    April 17, 2014 at 7:55 PM
  • RT @joemccann: Total Number of GitHub Repositories by Programming Language http://t.co/30cekDsE4s
    April 17, 2014 at 4:25 PM
  • JSF + AngularJS = AngularFaces? http://t.co/mXvOTwVbb6 // Interesting insight. Thoughts?
    April 17, 2014 at 3:45 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2013 Keyhole Software, LLC. All rights reserved.