Object-Oriented Javascript

24th May, 2006 @ 10:20am UTC

Development, JavaScript, Web / 43 Comments

Following on from my earlier post, “Object-Oriented Concepts,” it’s time we started to have a look at some examples of execution. I’m going to start with Javascript because I believe this to have widest appeal - PHP, as a server-side language, is probably of interest to fewer developers so I’ll cover it later.

So without further ado, here’s how to objectify your javascript…

Objects in Javascript

Although Javascript shouldn’t be classed as an object-oriented language, pretty much everything within it is object based; from DOM scripting (Document Object Model) through to specific built-in objects such as Image and Date. This basically means that we can adopt some OOP concepts but not all.

Javascript handles objects in a number of ways; a developer can define an object and then instantiate with the new operator, a developer can declare an object on the fly using the object literal or a developer can extend an existing object (either built-in or user-defined) using its prototype.

In fact, even data-types that can be declared literally, such as arrays and strings, can also be declared as objects. This is mainly so that object methods can be applied to literal values when needed. Javascript does this by temporarily converting your literal into an object. A good example would be the String.length method.

Sounding complicated? Don’t worry, it’s really very easy. Let’s start getting our hands dirty…

The Object Literal

In programmer-speak, a “literal” is any value declared literally. Good examples would be string literals, array literals and boolean literals - the literal is the part after the “=” assignment operator:

// String literal
var my_string = "2468 This is a string";

// Array literal
var my_array = ['element1', 'element2', 'elephant'];

// Boolean literal
var my_boolean = true;

As a developer, you probably use these methods day-in, day-out; it still amazes me, however, how many programmers I speak to that don’t know the correct terminology!

In Javascript, we can also declare objects as a literal:

function getArea(radius)
{
  // return the radius of our circle using the
  // PI attribute of the built-in Math object
  return (radius * radius) * Math.PI;
}

var circle = {
  radius : 9,
  getArea : getArea(this.radius)
};

Here we’ve defined an object, circle, with a radius of 9. If we wanted to obtain the area of our circle, we could use the following line of code:

var my_radius = circle.getArea();

Fantastic! We’ve got ourselves a circle; but what happens when we want to declare more circles, all with varying radii?

Imagine we want to create lots of circle objects using our object as a base - if we’ve declared using the object literal, we’re not able to do that! To a certain extent, that’s the difference between objects and classes (see my earlier post); if we want our object to behave more like a class (which, unfortunately, aren’t really supported in Javascript even though we can mimic the behaviour), we need to use objects that utilise the new operator.

Note: For more information on the object literal, I recommend reading Chris Heilmann’s “Show Love to The Object Literal,” and Dustin Diaz’s “JSON for the Masses.”

The new Operator

The new operator creates an instance of any built-in or user-defined object - basically allowing us to re-use a user-defined obect (much like the behaviour of a class). Here are a couple of examples using built-in objects:

// Create a date object
var obj_today = new Date();

// Preload an image using the Image object
var obj_supper = new Image();
obj_supper.src = 'thelastsupper.jpg';

Take note that Javascript’s built-in objects do not always use a proper class interface - ie. you can set attributes without using a method. In most OOP languages this is considered bad practice and you can often prevent it with the use of access modifiers (public, private, protected). Even though Javascript let’s us get away with this method when using its built-in objects, I personally tend to write a proper interface for my own objects.

Ok, so that’s how you declare using the built-in objects, but what about something user-defined?

When using the new keyword to declare user-defined objects, the objects require a constructor. Object structure (including an object’s constructor) is handled somewhat differently to most languages in Javascript. Here’s the syntax for defining this type of object:

function circle(radius)
{
  this.radius = radius;
  this.getArea = getArea;

  // Don't forget that a constructor should
  // always retain a valid state - so it should
  // always return true
  return true;
}

function getArea()
{
  // return the radius of our circle using the
  // PI attribute of the built-in Math object
  return (this.radius * this.radius) * Math.PI;
}

In the example above, you’ll notice that the syntax is almost completely identical to declaring a function. This function is the constructor of our object and attributes and methods are declared within it, using the this keyword.

Notice the Math object doesn’t need to be instantiated before we can use it - this is simply because it’s special and is always available for use.

We can now instantiate our object using the new operator as before:

var obj_pizza = new circle(9);

And we can work out the area of our circle using the following line of code:

var flt_area = obj_pizza.getArea();

Encapsulation

There is one problem with the above definitions of an object, however, and that’s the lack of encapsulation. If we were to include another piece of code that used a getArea() function (for instance a triangle object), our circle object’s getArea() method would be over-written. To better encapsulate our methods, we can define our objects either literally like so:

var circle = {
  radius : 9,
  getArea : function()
  {
    return (this.radius * this.radius) * Math.PI;
  }
};

Or non-literally like so:

function circle(radius)
{
  this.radius = radius;
  this.getArea = function()
  {
    return (this.radius * this.radius) * Math.PI;
  };

  return true;
}

In both cases this limits the scope of each getArea() method to each circle object.

Inheritance and prototype

The prototype property is a useful feature in Javascript - it basically allows us to add attributes or methods to an object. This is a form of inheritance.

As a quick example of prototype in use, let’s add a function to work out circumference:

function circle(radius)
{
  this.radius = radius;
  this.getArea = function()
  {
    return (this.radius * this.radius) * Math.PI;
  };

  return true;
}

// Add our new method
circle.prototype.getCircumference = function()
{
  return this.radius * Math.PI * 2;
}

// Instantiate our object
var my_pizza = new circle(9);

// Call our new method
var flt_pizza_circ = my_pizza.getCircumference();

“But wait, ” I hear you cry, “what if we want to inherit and entire object?”

Not a problem, prototype can handle this like so:

// Declare two objects - we're going to want Lion to
// inherit from cat
function cat()
{
  this.eyes = 2;
  this.legs = 4;
  this.diet = 'carnivore';

  return true;
}

function lion()
{
  this.mane = true;
  this.origin = 'Africa';

  return true;
}

// Now comes the inheritance
lion.prototype = new cat();

// We can now obtain lion.diet
var simba = new lion();
var simba_diet = simba.diet;

Ok, so now that we understand inheritance (you do understand, right?), let’s take a look composition.

Composition

Association

Association, in Javascript, is pretty straight forward. Here’s an example:

// Define an object
function brick()
{
  return true;
}

// Define an object
function wall()
{
  this.brick1 = new brick();
  this.brick2 = new brick();
  this.brick3 = new brick();

  return true;
}

Just like the pseudo-code example in my earlier post, we can see that the object “wall” now contains three instances of the “brick” object. This is association - the wall object “has” three bricks.

Now let’s take a look at aggregation.

Aggregation

Aggregation, as a relationship, is reliant on the ability to pass object and function parameters by reference. This basically means that a parameter represents a pointer to the actual object passed and not just a copy. Thankfully, Javascript handles all parameters in this way - which makes our aggregation relationship nice and easy:

function person
{
  return true;
}

function car(driver)
{
  this.driver = driver;

  return true;
}

var me = new person();
var myMotor = new car(me);

This relationship allows us to “use” the “me” object within our “myMotor” object. We could also use the “me” object in any other objects that require it - and we’d only need that single instantiation. This is immensely helpful when we’re using objects that control behaviours such as XmlHttpRequest.

Update: Thanks to Jonathan Snook, I’ve recently discovered that Javascript doesn’t pass all parameters by reference - in fact working out how Javascript has handled your parameter can be quite confusing. In our particular case, the parameter is passed by reference because it is an object. When we’re not working with objects, this might not be the case. For more detailed information, please take a look at Jonathan’s excellent article, “Javascript: Passing by Value or by Reference.”

Update 2: Stefan Van Reeth’s fantastic comment, below, looks at references in a little more detail. I definitely recommend reading it as his explanation and examples may clear up confusion.

Polymorphism

Due to it’s object-based nature, Javascript handles polymorphism very well. Take a look at the following example:

function Person() {
  //...
  this.Speak() {
    // ...
  }
}

function Employee() {
  // ...
  this.Speak() {
    // ...
  }
}

AND (!!!)

Employee.prototype = new Person(); // inheritance
user emp = new Employee();
emp.Speak();

Employee inherits from Person and, as a result, already has a Speak() method. Because we want the Speak() method in Employee to do something different, we overload it with a new method definition. This is polymorphism in action.

Update: My original example for Polymorphism was entirely incorrect. Thanks go to “Joe is all you need to know” for pointing out my error and supplying this correct example.

Summary

So that’s a brief guide to adopting OOP practices in Javascript; I think you’ll agree that it adds real power when dealing with complicated scripts. However, that raises a common issue with OOP - you shouldn’t just use it for the sake of it. In fact, I often find that developers who are using these practices for everything are often the same developers who don’t understand the concepts fully.

My next OOP post will be regarding object-oriented PHP but, after an inquisitive email from Nate Logan, I also intend writing a piece about abstraction - the practice of reducing a process down to it’s root concepts and modelling them in the programming language of your choice.

Like this post? Digg it, Del.icio.us it, Ma.gnolia it!

Comments (43)

Skip to the comment form…

  1. Gravatar Image cmilhench May 24, 2006 @ 11:56 am

    with

    
    // Now comes the inheritance
    Lion.prototype = new Lion();
    

    surely you mean

    
    // Now comes the inheritance
    Lion.prototype = new Cat();
    
  2. Gravatar Image Tim May 24, 2006 @ 12:00 pm

    @cmilhench: Well spotted - you’re absolutely right. You’d think I could proof-read my own posts, wouldn’t you?

    Have fixed it.

  3. Gravatar Image emilk May 24, 2006 @ 1:04 pm

    hi,
    my memory is not perfect, please remind me,
    is there or not any problem with memory leaking in ie, when one uses method encapsulation like you did with getArea in the case of circle.

  4. Gravatar Image JJS May 24, 2006 @ 1:09 pm

    First, being quite unfamiliar with OOP, both your articles are eyeopeners, or better ‘illuminators’Â :)

    Also, in example illustrating association, it seems that a brick is missing in the wall (three instead of four).

    Big thanks,

    JJS.

  5. Gravatar Image Tim May 24, 2006 @ 1:19 pm

    @emilk: To be honest, I’m not sure - if I remember correctly, memory leaks occur as part of a circular reference in IE. I don’t see that encapsulation will cause the same problem…

    Of course I could be completely wrong; anybody out there able to confirm?

    Update: Here’s an interesting document about IE memory leaks, hosted over at MSDN.

    @JJS: Gah! That’ll teach me not to change my examples right before I publish! Thanks very much - have fixed it.

  6. Gravatar Image pbb May 24, 2006 @ 8:55 pm

    I also found the the two posts interesting, but I would find it helpful if it were possible to demonstrate a way of putting the theory into practise.
    Do you have any working examples where you have used these principles to produce an OO Javascript system?
    At the moment, I can’t see clearly how one would go from your (simple) examples to something more ‘real world’.

  7. Gravatar Image Mike May 25, 2006 @ 1:27 am

    Thanks, I was pretty much oblivious to JavaScript and OOP before, I knew it basically existed, but never how to implement it myself. Nice tutorial! :)

  8. Gravatar Image Cody Lindley May 25, 2006 @ 2:09 am

    Thank you, we need more people (like you) explaining in their own words how OOP works in JS.

  9. Gravatar Image ohyeahohare May 25, 2006 @ 2:43 am

    Hey,

    First of all, love the L&F of the site. I’m from Digg.

    I’m having problems with what I believe to be encapsulation with some ‘AJAX’ code i’m trying to implement.

    Basically I have a 2 functions and a ‘global variable(its declared in the .js file, not within a function( and the first function sets the variable, while the second tries to read it… but for some reason it’s always undefined… even though I have set it previously. I’ve used alerts to prove it’s being set correctly and everything!

    Any Ideas?

  10. Gravatar Image kruzes May 25, 2006 @ 4:39 am

    “Although Javascript shouldn’t be classed as an object-oriented language (…)” My God… how can people spread such nonsense!?

  11. Gravatar Image TechMag May 25, 2006 @ 7:41 am

    Good tutorial. Thnaks to you.

  12. Gravatar Image Brian May 25, 2006 @ 9:58 am

    Fantastic article, thanks! I’ve been a programmer for nearly 10 years and code (well) in everything from C to PHP to Shell Script and learned just by doing. OO programming in JavaScript is something I do everyday, but not being formally trained, I never knew terms like polymorphism or aggregation in relation to code, so that part was most interesting to me.

    Nice work!

  13. Gravatar Image Tim May 25, 2006 @ 10:42 am

    Thanks for all the comments guys.

    @ohyeahohare: Sounds like you have a variable scope problem - have a look at Mozilla’s guide to Javascript variable scope

  14. Gravatar Image Tim May 25, 2006 @ 11:23 am

    @kruzes: Having read through the comments left against my post on Digg.com, it would seem this initial statement is up for discussion. :-)

    I’m still firmly of the opinion that Javascript is not an object-oriented language even though most OOP features are available.

  15. Gravatar Image krouskop May 25, 2006 @ 3:26 pm

    “I’m still firmly of the opinion that JavaScript is not an object-oriented language even though most OOP features are available.” Exactly what Object Oriented Programming features are NOT available — or put another way, how exactly do you define “Object Oriented Language” such that ECMAScript/JavaScript does not fit in?

    I like the definition for OOP on Wikipedia:
    “The idea behind object-oriented programming is that a computer program may be seen as comprising a collection of individual units, or objects, that act on each other, as opposed to a traditional view in which a program may be seen as a collection of functions, or simply as a list of instructions to the computer. Each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine or actor with a distinct role or responsibility.”

    Objects in JavaScript certainly can do all of the items laid out in that definition (encapsulation, sending/receiving messages, etc).

  16. Gravatar Image Nikren May 25, 2006 @ 3:41 pm

    I have to agree with Kruzes on the object-based vs. object-oriented debate. A language must provide four basic capabilities to developers before it can be considered object-oriented:
    1. Encapsulation — the capability to store related information, whether data or methods, together in an object
    2. Aggregation — the capability to store one object inside of another object
    3. Inheritance — the capability of a class to rely upon another class (or number of classes) for some of its properties and methods
    4. Polymorphism — the capability to write one function or method that works in a variety of different ways
    JavaScript supports all four of these capabilities and thus is a truly object-oriented programming language.

  17. Gravatar Image Tim May 25, 2006 @ 4:01 pm

    Hmmm… Ok, Javascript definately fits that description of an object-oriented language - maybe you guys are winning the argument. ;-)

    Everything you create in Javascript inherits from the built-in Object class. It’s that class that contains the prototype method that opens up the world of prototype-based programming (and therefore flexibility) we’re all so fond of. For me, this isn’t the standard behaviour of an object-oriented language - objects should be statically typed, as should strings and other data-types.

    Having done a little browsing around other OO Javascript tutorials and articles, it seems to be a mixed-bag of opinions. To be honest, I’m really not all that bothered which definition fits it the best…

    Needless to say, whether it’s object-based OR object-oriented, the object functionality in Javascript is powerful and under-appreciated IMHO.

  18. Gravatar Image dennis May 25, 2006 @ 6:19 pm

    Hmm…if you think objects have to be statically-typed for the language to be considered “object-oriented,” then you exclude Smalltalk, which invented the entire concept. Alan Kay, who created it, has publicly scoffed at C++’s object-orientedness.

    Despite its dynamic typing, Smalltalk is class-based…for more examples of prototype-based languages, check out http://www.iolanguage.com and slate.tunes.org. Seems to be a fairly active area of development.

  19. Gravatar Image Ben May 25, 2006 @ 7:26 pm

    Classical Inheritance in JavaScript by Douglas Crockford may be of interest.

    http://www.crockford.com/javascript/inheritance.html

  20. Gravatar Image Ben May 25, 2006 @ 7:29 pm

    Not to mention some of his other articles,

    JavaScript: The World’s Most Misunderstood Programming Language
    http://javascript.crockford.com/javascript.html

    Private Members in JavaScript
    http://javascript.crockford.com/private.html

  21. Gravatar Image Tim May 27, 2006 @ 10:59 pm

    @Ben: Thanks for those - they were excellent reading!

  22. Gravatar Image Ravindra May 30, 2006 @ 6:28 pm

    I loved reading the whole article and comments. It’s very lucid as its font and format is. I feel Association is not very correctly defined. What is called here as an association is actually another form of aggregation (by value). I think association is more about cardinality among objects, which itself could be again by value and by reference.

  23. Gravatar Image Dafin June 6, 2006 @ 10:29 am

    Thanks, informative article, I know Java quite well and never knew that Javascript handles polymorphism and aggregation in quite a similiar fashion. Handly for developing some tasty AJAX….

  24. Gravatar Image Jeff July 27, 2006 @ 6:22 pm

    I am working on an attempt to make OOP in Javascript more elegant and provide some features and error detection many have become familiar with in more strict languages like Java and C++. It is still in its early stages, so please check it out and provide some feedback:

    http://www.uselesspickles.com/blog/the-class-library/

  25. Gravatar Image Stefan Van Reeth January 18, 2007 @ 5:44 am

    Nice introduction to OOP, but one small remark:

    “Aggregation, as a relationship, is reliant on the ability to pass object and function parameters by reference. This basically means that a parameter represents the ACTUAL object passed and not just a copy.”

    Nope, that’s not entirely true. Not wrong either :). What I mean is that your explanation is a bit dodgy. More correct would be:

    “Aggregation, as a relationship, is reliant on the ability to pass object and function parameters by reference. This basically means that a parameter represents a POINTER to the actual object passed and not just a copy.”

    Passing parameters by reference means exactly what it says: passing a reference to something as a parameter. Guess you phrased it like that to make the tutorial more accessible, but in the end I feel it’s more confusing than helpfull. When grasping a concept, it’s best to learn it right the first time. I know it’s all a bit abstract, but a tutorial should be entirely correct, not close enough ;).

    When an object gets passed to a function, Javascript passes not a copy of it (as in passing by value), but a placeholder for the object. To put it in real simple terms: the object is never “moved” from it’s place, only a “remote control” is provided. And as such, when you work with the parameter in the function, it seems you are working with the object itself there. But in fact you are working with the remote.

    Time for some example:

    function Car()
    {
    this.accelerate = function(howFast) { // accelerate code };
    }
    var myCar = new Car();
    myCar.accelerate("gently");

    So now we have an object called myCar that’s an instance of the class Car. It has a method called accelerate and we can pass the amount of acceleration to that. So far so good I think.

    function stealCar(someCar)
    {
    someCar.accelerate("reallyFast");
    }

    The function stealCar does one thing: riding off really fast with a car object. And this function works on any car we find, umm, define :). And now we come to the real explication.

    stealCar(myCar);

    When we invoke the function (e.g. steal a car), the object myCar get’s passed by reference. Or better, we say in code: “See that car there where I point to? Steal it.” Where “that car” would be the reference, or pointer. In this case it happens to be myCar. Inside the function we can use methods and properties of myCar through the “remote” called someCar. And someCar is neither a copy of the original object, neither the object itself. It’s a direction to it.

    Hope that was a bit clear. I guess that’s the most difficult thing in OOP: learning to think in abstract terms. I still do it by imagination: I build up a “picture” of the situation in my mind. But quite frankly, I don’t even know how to explain that process in normal language.

  26. Gravatar Image Tim January 18, 2007 @ 8:32 am

    @Stefan: Thanks very much for that comment - it’s nice to get some serious value out of the discussion. It’s also nice to get a heads-up when people think stuff might be confusing! :)

    Passing parameters by reference means exactly what it says: passing a reference to something as a parameter. Guess you phrased it like that to make the tutorial more accessible, but in the end I feel it’s more confusing than helpfull.

    I think you’re right about this so I’m changing the text in the tutorial - I’m also going to link to your comment because it adds to my original text quite nicely.

  27. Gravatar Image zack February 7, 2007 @ 8:07 am

    dang… you guys are smart. thanks for explaining this!

  28. Gravatar Image ordinarywebguy March 8, 2007 @ 2:49 am

    I as messed with OOP in other programming languages such as Java and C++, I found the convenience of getting everything organize when using object. As we developers know, javascript is a loosely type language and as I messed with core javascript it got me frustrated because of lacking its OOP capability as I always wanted to execute my coding in an organized way but as I read with this article, it enlightens me with javascript OOP.

    Thanks Tim for this wonderful article about javascript OOP and I’m waiting to read your upcoming entry which is PHP OOP.

    Thanks again! Ciao!

  29. Gravatar Image Prasad May 29, 2007 @ 2:44 am

    Hi ,
    could you tell me :
    How to add an attribute using dom.

    for example:
    function divobj(w,h,l,t) {
    this.div = document.createElement(’div’);
    this.wid=w; this.he=h;this.lef=l; this.to=t;
    display=function() {
    this.div.style.width=this.wid;
    ……this.style.top = this.to;
    };
    }

    to this using prototype I want to add “id” property which I tried this way:
    this.id_ = id and added one extra argument in div(argument list).
    and
    in the display function:
    I added:
    this.div.setAttribute(”id”,this.id_);
    is this correct…could you give me some suggestion:where I am making mistake?
    thank you.
    Prasad.

  30. Gravatar Image Joe is all you need to know. October 18, 2007 @ 9:26 am

    The last code snippet in this article doesn’t really show polymorphic behavior. circle and rectangle are two distinct constructors and thus creates two distinct and non-related objects.

    If you were to do something like:

    function Person() {
      //...
      this.Speak() {
        // ...
      }
    }
    
    function Employee() {
      // ...
      this.Speak() {
        // ...
      }
    }
    
    AND (!!!)
    
    Employee.prototype = new Person(); // inheritance
    user emp = new Employee();
    emp.Speak();

    Here, it’s polymorphic because based on the object, the correct Speak() will be called. If Employee didn’t have a Speak() method, Person’s Speak() will be called instead. There’s nothing polymorphic having two non-related objects having the same method.

  31. Gravatar Image Tim October 21, 2007 @ 10:38 am

    @Joe: Gah! You’re absolutely right! That’s one hell of a mistake; thanks for bringing it to my attention!

    I shall update, and attribute it accordingly! :)

  32. Gravatar Image Tom December 7, 2007 @ 10:02 am

    Excellent article on OO concepts in javascript. Being an ajax developer myself and with the ajax explosion, it makes sense people adapt a more OO approach to there javascript

  33. Gravatar Image madlen January 29, 2008 @ 5:50 pm

    Thanks nice, informative article, I know Java quite well and never knew that Javascript handles polymorphism and aggregation in quite a similiar fashion. Handly for developing some tasty AJAX….

  34. Gravatar Image deltawing1 March 17, 2008 @ 8:17 am

    Hey thanks for the article :)

    I always wondered what prototype meant. Javascript does OOP concepts in a really strange way, it really broadens the mind :)

  35. Gravatar Image Peter Laman May 16, 2008 @ 10:01 am

    Thanks for your article. Coming from a Delphi background, it’s nice to see there’s a bit of OO in JS. What I haven’t found - and I don’t know if it even exists, is a real override of methods, instead of overloading it. That is, I want to derive object B from object A. A has method X and I want to retain that in B, but I want to add some code to it. Is that possible in JS?

  36. Gravatar Image Nick Nguyen May 31, 2008 @ 10:06 pm

    Hi there, I just tested your codes below and it does not work as you stated.The this.radius can’t be passed if I want to pass the property radius. The “this” is pointing to the window object. I tried to pass getArea : getArea(this) and add alert(radius); inside the getArea() function and it displays object window, so that “this” doesn’t point to the circle object.

    function getArea(radius)
    {
      // return the radius of our circle using the
      // PI attribute of the built-in Math object
      return (radius * radius) * Math.PI;
    }
    
    var circle = {
      radius : 9,
      getArea : getArea(this.radius)
    };
  37. Gravatar Image Paul August 6, 2008 @ 9:58 pm

    Thanks for the article. I was looking around at a few similar overviews online and noticed some differences.

    Firstly, when defining a method for an object you did it in the object’s constructor, whereas some other people did it like this:

    
    function Pet(name) {
        this._name = name;
    }
    
    Pet.prototype._name;
    
    Pet.prototype.getName = function() {
        return this._name;
    }

    citing this as "the recommended syntax for defining the properties and methods that your JavaScript class will expose" (I guess it applies to properties as well as methods)

    Secondly, when dealing with inheritance, some other sources seemed to explicitly call the parent object’s constructor from the constructor of the child object. e.g.

    
    function Dog(name) {
        Pet.call(this, name);
    }
    

    are these differences significant?
    Thanks

    (quote and code snippets from: http://www.xml.com/pub/a/2006/06/07/object-oriented-javascript.html)

  38. Gravatar Image Tim August 7, 2008 @ 9:49 am

    @Paul: I’m afraid this article is rapidly going out of date. The article you reference is, indeed, correct — using prototype to apply properties and methods to an object is generally much faster and is the preferred method.

    In fact, the way I do it these days is like this:

    function Pet(name, sex) {
      this.name = name;
      this.sex = sex;
      return this;
    }
    
    Pet.prototype = {
      getName: function() {
        return this.name;
      },
      getSex: function() {
        return this.sex;
      }
    }

    This saves you having to declare Pet.prototype before each of your member declarations, whilst still maintaining the speed of prototype assignment.

    As for you second point about inheritance, I’ve seen this method used as well; however prototypal inheritance is a key feature of JavaScript and, apart from being much faster, allows a greater degree of flexibility.

    My article was originally intended to introduce traditional OO techniques to new JavaScript developers. It’s worth noting that, as I stated earlier, the article is going out of date fairly rapidly. It’s also worth noting that JavaScripts objects are quite different to traditional OO languages and, as such, have a large range of different characteristics; and subsequently are able to utilise a number of wildly different techniques.

    Hopefully soon I will get around to writing a new, more up-to-date analysis of coding with JavaScript — I’ve been on a year long break from blogging so I’m a bit out of practice. :)

  39. Gravatar Image Paul August 7, 2008 @ 6:02 pm

    haha. Well, thanks for the update and speedy reply.

  40. Gravatar Image Jason October 8, 2008 @ 6:26 pm

    @Tim - With object oriented event handling, if you’re using a bind() function for scope reasons, there are some advantages to using the old syntax.

    http://simpletutorials.com/?path=tutorials/javascript/events/oop_handler

  41. Gravatar Image Sukdev Garai November 18, 2008 @ 2:33 pm

    I have used this in our application….This is helpfull

  42. Gravatar Image vishal shah January 24, 2009 @ 7:34 am

    nice tutorial it help me alot to learn oop and javascript concepts thanks.

  43. Gravatar Image aleemb March 18, 2009 @ 8:55 am

    Why is it that constructors should return true? Examples and tutorials I have seen elsewhere don’t mention this and I cannot produce any use-case scenarios where exclusion of ‘return true’ at the end of constructors would cause an issue? Could you provide an example where exclusion or ‘return true’ from constructors would cause issues?

Leave a comment





Categories

Syndication

Technorati

© 2009 Tim Huegdon, All Rights Reserved / Website design and development by Nefarious Designs

Powered by Wordpress / Log in

Caution: May contain traces of the undead.