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() { return “I am ” + this.name; }; // return this; };
September 14th, 2009 at 1:18 pm
[…] Exploring common JavaScript patterns and anti-patterns « Constructors […]
September 14th, 2009 at 1:28 pm
[…] constructor is just a function and failing to invoke a constructor with new leads to errors. Not syntax errors […]
September 14th, 2009 at 1:41 pm
[…] you add properties to the prototype of a “normal” function, meaning function that you don’t invoke as a constructor, these will not be […]