javascriptoopreturnnew-operator

Is there any reason to manually `return` in a constructor function?


Typically, in a constructor function, the object that is bound to this within the function is returned by it when it is called with the new prefix. But I would imagine that it's also possible (I think I even read this in crockford's book) to manually return your own value. Are there any places where such a practice is useful?


Solution

  • If you return a value type from the constructor, you'll get different behavior depending on if new was used. That's how String works. Look at this object in your JavaScript console:

    {
        s: String("abc"),
        S: new String("abc")
    }
    

    Little s contains a string value, but big S contains a string Object. A subtle difference, perhaps.

    You could go way beyond that and use the same function for different purposes:

    function Foo() {
        return "abc";
    }
    Foo.prototype.DoSomething = function () {
        // something completely unrelated to "abc"
    };
    var a = Foo();      // The string "abc".  Does not have a DoSomething() method.
    var b = new Foo();  // An Object with a DoSomething() method.  Doesn't know about "abc".
    

    Depending on whether new was used, you'd get back something completely different.