Constructor functions

The object literal syntax is great for setting up one off objects but sometimes you’ll want to mass produce objects that all have the same properties and methods. It would be a pain to have to set up each object individually so instead you can use a constructor function to do it for you.

There’s nothing that makes a constructor function different from a regular javascript function. It’s just an ordinary function that has the logic needed to create a new object instead of regular program logic. It’s not a special language construct like a class is in Java or C#.

Here’s a simple example of a constructor function for building a pet object:

  1. function Pet(name, species, hello){
  2.     this.name = name;
  3.     this.species = species;
  4.     this.hello = hello;
  5.     this.sayHello = function()
  6.     {
  7.         alert(this.hello);
  8.     }
  9. }

Notice that the logic inside the constructor function is almost exactly the same as the logic for building a simple object. The only difference is that the properties are being assigned to “this” rather than to a newly created object. The this keyword is a special javascript operator that gives you a reference to the object that is being created. This is called the function’s context.

The new operator

The constructor function itself won’t create a new object. You need to call it with the new operator. The new operator takes care of creating a new object, passing it to the constructor function and returning it when the function is finished.

The syntax should look pretty familiar to most OO programmers, particularly anyone with a C# or java background:

  1. var rufus = new Pet("Rufus", "cat", "miaow");
  2. rufus.sayHello();

Complete sample

You could actually call any javascript function with the new operator and it would act in the same way. Functions that aren’t constructors would just return an empty object because they wouldn’t have the logic for instantiating the object.

Objects maintain a link to the function that created them

The only difference between an object created by a constructor and an object created from scratch is objects created by constructor function always maintains a link back to the function that created it.

You can find out what an object’s constructor was by accessing it’s constructor property. The constructor property of an object that’s not created with a custom constructor function will point to the Object constructor.

  1. var rufus = new Pet("Rufus", "cat", "miaow");
  2. alert(rufus.constructor.toString());

Complete sample

This is important for supporting javascript’s prototypal inheritance.

Constructor functions aren’t classes

Constructor functions look a lot like classes in other languages but they’re not. In a language like Java or C# a class is synonymous with a data type. It gives you guarantees about what properties and methods the instances of the classes will have.

All a constructor function gives you is an object that has been instantiated in a particular way. After that the object can then be changed in whatever way you want. It is not obliged to be anything like the other objects that were created by the constructor function. There is no promise that it will contain any particular properties or methods.

What’s next?

This article is part of a set of related posts about using javascript objects. This article is part of how javascript objects work.

This article is part of a set of related posts about How javascript objects work.

Comments

  1. Plodoc Says:

    I think that every object will get a different copy of the sayHello function if you declare it in the constructor. If we want to mass produce objects, shouldn’t we add the function to the Pet’s prototype ?

  2. Helen Says:

    Yeah that’s right. :) I’m going to talk about prototypes in a couple of weeks.

  3. ted devito Says:

    if you use object literals to define an object, can you instantiate new instances of that object? is there a key name as a constructor?

    var myObj = {
    dog:{},
    cat:[],
    goat: function(){},
    construct: function(params) {}
    }

    var instances = [], i = 0;

    do {
    instances.push( new myObj(params) ), i+=1;
    } while (i < 10)

    BY THE WAY, this is one of (well, tonight it’s definitely the best!) javascript object tutorials i’v e found. Your stuff is complete, clear and well written.

  4. Helen Says:

    Glad you liked the article. :)

    You can’t just use the new operator with an object. It will only work with a function. This is because the constructor function will have logic in it to construct an object. It’s not just cloning an existing one.

    If you wanted to clone an existing object, you could iterate through all of its properties and copy them into a new object:
    var person =
    {
    prop1: “one”,
    prop2: “two”
    }
    var person2 = {};
    for(var property in person)
    {
    person2[property] = person[property]
    }
    alert(person2.prop1 + ” ” + person2.prop2);

    There’s an interesting article about doing this (make sure you check out the discussion) http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone

    Another way to do it is to use javascript’s prototype chaining feature to make one object “inherit” from another:
    function clone(existing)
    {
    var constructor = function() {};
    constructor.prototype = existing;

    return new constructor();
    }
    var person3 = clone(person2);
    alert(person3.prop1 + ” ” + person3.prop2);

    It’s a bit more complicated than regular inheritance, javascript isn’t a class based language like java or C#, but it’s a similar general idea. This is an idea that I want to talk about in a future article but there’s plenty of good information about it on the web. Try googling for javascript prototype inheritance and javascript prototype chaining.

    Thanks for the interesting question. :)

  5. ted devito Says:

    Yeah, it gets a little boggling. I found some crazy stuff on inheritance. Just an FYI, here’s two pages that stood out:
    http://ajaxpatterns.org/Javascript_Inheritance — a wiki with a good summary
    http://javascript.crockford.com/inheritance.html — douglas crockford on inheritance (recommended by john resig)

    After looking around at your tutorials and some of the links you recommended, I think what I was trying to do was something like this… The goal being to create multiple instances of an object that is populated with properties, but then each instance can have different local values to work with.

    var existing = {prop1: ”, prop2: [], prop3: {}, prop4 : function (){} };
    var constructor = function (a,b) {this.a = a; this.b = b;};
    constructor.prototype = existing;
    var instances = [], i = 0;

    do {
    instances.push( new constructor(i,somevar) ), i+=1;
    } while (i < 10)

    for (var i in instances) alert( instances[i].prop1 );

  6. Javascript prototype chaining - Helephant.com Says:

    [...] Constructor functions have a property called prototype. Adding properties and methods to the prototype property will automatically add the method or property to all objects created by the constructor function. [...]

  7. Javascript method context – Helephant.com Says:

    [...] the previous examples you might have noticed that we use this to get a reference to the object that a function belongs to [...]

Leave a Reply