When should I automatically create an object even if `new` is forgotten?

Viewed 1228

Let us say I have the following object constructor:

function Foo(bar) {
    this.bar = bar;
}

If I run the function in the global scope without the new keyword then bar will be set in whatever scope Foo() is called in:

var foo = Foo(42);
console.log(bar); // 42
console.log(foo.bar); // ERROR

So my idea is to do something like this:

function Foo(bar) {
    if(!(this instanceof Foo)) {
        // return a Foo object
        return new Foo(bar);
    }
    this.bar = bar;
}

That way if I do new Foo(42) or Foo(42), it would always return a Foo object.

Is this ever a good idea? If so, when? When (and why) would it be wise to avoid this technique?

4 Answers
Related