There is a major feature of Javascript that is sorely misunderstood–the “new” keyword. Using the “new” keyword when declaring a variable will assign it’s value to the state of “this” upon completion of the function. Not using “new” will simply assign it’s value to the return value, or ‘undefined’ if nothing was returned. I wrote a simple example below to illustrate the effects of using the new keyword.

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return name;
}

var test = new Test('test');
test instanceof Test; // returns true
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.

var test2 = Test('test');
test2 instanceof Test; // returns false
test2.test(); // throws TypeError: Object #<Test> has no method 'test'
test2 // returns 'test'

As Andrew kindly pointed out; if you return an object the resulting value will be an instance of the returned object rather than the constructor.

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return {name:name};
}

var test = new Test('test');
test instanceof Test; // returns false
test2.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns {name:'test'}.
Be Sociable, Share!