Alex Rivera | Logout

What difference is there in JavaScript between a constructor function, and function returning object which is invoked as a constructor?

Asked 2012-04-26T06:44:39.863
11

I know this is not the recommended way of doing it, but if I declare the following functions, and then invoke them as constructors, what will be the difference (if any) between the resulting objects?

function Something() {
    this.foo = "bar";
}

function something2() {
    var that = {};
    that.foo = "bar";
    return that;
}

var x = new Something();
var y = new something2();
var z = something2();

I.e. what will differ between x, y and z here?

Wouldn't something2 be a much better way of writing the constructor, since whether you use new or not will not affect the result of the function?

BTW should something2 be capitalized here? (I assume not since Crockford is so adamant on the capitalization, for functions will clobber the global namespace...)

Edit
Report

1 Answer

1

Invoking a function as a constructor (i.e. with the new keyword) runs the following steps:

  1. create a new object
  2. set the prototype of that object to the object in the prototype property of the function
  3. execute the constructor function in the context of that object (i.e. this is the new object)
  4. return that object (if the constructor has no return statement)

So, your second solution will just return a plain object with a property "foo". But neither y nor z are instanceof Something2 and don't inherit from that prototype. There are functions like that, yes, but they should not be called constructors (no uppercase naming, no invokation with new). They belong to the factory pattern.

If you want a constructor which can be executed without new, use that code:

function Something(params) {
    if (! this instanceof Something)
         return new Something(params);
    // else use "this" as usual
    this.foo = "bar";
    ...
 }
answered 2012-04-26T06:56:24.810

Your Answer