About Javascript Constructor pattern

I’m going to try to explain (to myself and some stumbling web surfer) the constructor pattern in Javascript.

Javascript objects inherit properties directly from other objects, and all the way back to the builtin Objects’ prototype. If we create an object by invoking functions, their this keyword is bound to the object whose method created it. Also, all inner properties, and the closure scope will be shared.
Tipically it’s done this way:

var myObject = {
prop: 0, // defaults to 0
add: function (x) {
this.prop += x;
}
};

var otherObj = myObject;
myObject.add(2);
console.log(myObject.prop); // 2
otherObj.add(3);
console.log(otherObj.prop); // 5

So, all objects’ this keyword is bound to that one object.

If we want separate multiple objects, we use the constructor pattern. By convention, we name the constructor functions with a capitalized names.
Here is an example:

// “class” definition
var MyClass = function () {
this.prop = 0;
};

// lets add a getter method
MyClass.prototype.add = function (param) {
this.prop += param;
};

var myInstance = new MyClass();
var otherInstance = new MyClass();

myInstance.add(2);
otherInstance.add(3);

console.log(myInstance.prop); // 2
console.log(otherInstance.prop); // 3

 

When we invoke the object with the new pattern, its this keyword is bound to that object, so every object gets its own closure space.

P.S. I’ve ran into an interesting question on StackOverflow in this comment, so I made a post to try to answer it.

Leave a Reply