Constructors

A simple way to create objects in JavaScript is using object literal notation. An other way, a bit more involved is to use a constructor function.

var adam = new Person("Adam");
adam.say(); // "I am Adam"

The invocation of the constructor looks a bit like a class in other languages, but the constructor is still just a function. (JavaScript doesn’t have classes). So the constructor is the blueprint, the recipe for the object.

And here's how the constructor Person is defined, it adds all members to the this object.

var Person = function(name) {

  this.name = name;
  this.say = function() {
    return "I am " + this.name;
  };

};

When you define a constructor, something like the following happens behind the scenes. It's as if you defined an object using the literal notation and then returned it.

var Person = function(name) {
  // var this = {};
  this.name = name;
  this.say = function() {
    returnI am ” + this.name;
  };
  // return this;
};

Tags: ,

3 Responses to “Constructors”

  1. JSPatterns.com » Blog Archive » Constructor naming convention Says:

    […] Exploring common JavaScript patterns and anti-patterns   « Constructors […]

  2. JSPatterns.com » Blog Archive » Enforcing `new` in constructors Says:

    […] constructor is just a function and failing to invoke a constructor with new leads to errors. Not syntax errors […]

  3. JSPatterns.com » Blog Archive » Prototype Says:

    […] you add properties to the prototype of a “normal” function, meaning function that you don’t invoke as a constructor, these will not be […]

Leave a Reply