Scope Safe Constructors in Javascript

Last modified: 
Thursday, April 9th, 2015

Scope-safe constructors ensure Javascript objects created without the ''new'' keyword will still behave as expected as regards scoping.

function MyClass(someValue) {
    if (this instanceof MyClass) {
        this.someValue = someValue;
    }
    else {
        return new MyClass(someValue);
    }
}

If you don't use scope-safe constructors and unwittingly instantiate an object without the new keyword, this will be in the global scope.

function MyClass(x) {
    this.x = x; 
}

// Here AnObject has been instantiated without the "new" keyword.
var AnObject = MyClass(5);

// It seems to work as expected, but...
console.log(AnObject.x); // 5

// ...what happens set a value to x while in the global scope?
x = 12;

// The value of AnObject.x is updated to 12, thus encapsulation is broken!
console.log(AnObject.x); // 12


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.