Aug 24

Using functions as constructors

Posted in Javascript      Comments Off on Using functions as constructors

In a previous post, we’ve already met an easy way of creating objects through literal objects (which I personally prefer to call anonymous objects). Unfortunately, there were some shortcomings to that strategy: things didn’t work quite well when we needed to add methods that should be used for specific types of objects.

Today we’re going to see how we can use functions as constructors. The idea is simple: we add a new function which defines the expected parameters and then we instantiate a new object by using the new operator.  Here’s a snippet which reuses our previous OO example:

var User = function(name, address) { = name;
    this.address = address;
var user = new User("Luis", "Funchal");
alert( + "-" + user.address);

If you run the previous snippet, you’ll see that you’ll get a message with the user’s name and address. Functions are really interesting objects! If you recall our previous discussion on the Object type, you probably remember that all objects have a prototype object. Since functions are objects too, they also have their own prototype object. This object has a special property called constructor which references the function itself. That means that the following line will always yield true:

alert(user.constructor === User);

The constructor property (it would be probably better to call it function because it does  reference a function) is really interesting and you can use it in fairly advanced scenarios. For instance, you can use it for emulating overloads (more about his in future posts).

Notice also that the function prototype object is also “linked” to the Object’s prototype object (you can easily check this by using the code I’ve shown in a previous post – don’t forget that expanding the Object’s prototype property is really a bad bad bad thing to do).

Now, since we’re building new instances from functions, it’s “safe” to expand the prototype with helper methods. In fact, this is one of the recommended approaches you should take when building new “types” in JavaScript. For instance,here’s a method that concatenates the name and address of a user:

User.prototype.sayHi = function() {
    return + "-" + this.address;
var user = new User("luis","funchal");

The advantage of doing this is that the sayHi method will only be available to instances created through the User constructor. In other words, if you create another function constructor (ex.: Student), you’ll see that you won’t be having any sayHi method because that method was only added to the User’s prototype object. And that’s it. Keep tuned for more on JavaScript.