user4316237
user4316237

Reputation:

Returning constructor function does not produce constructor function

I want to create an ad-hoc constructor with the following code,

    var foo = function() {
        var bar = {
        a : 3,
        b : {c: 4, d: {e: 5}}
        };

        var f_ = function() {};

        f_.prototype = bar;

        return f_;
    }

From my understanding, foo should return a function that can be used as a constructor, like so var baz = new foo However, the constructor returns a function, not an object. I can see prototype from the function returned,

    >baz.prototype
    { a: 3, b: { c: 4, d: { e: 5 } } }

So, my question is, why isn't foo returning a constructor?

Upvotes: 1

Views: 30

Answers (1)

dfsq
dfsq

Reputation: 193301

You need to make a slight modification to your code. If you want foo to be a constructor function then make sure it's an immediate function in the first place, which returns a new constructor function:

var foo = function() {
    var bar = {
        a: 3,
        b: {c: 4, d: {e: 5}}
    };

    var f_ = function() {};

    f_.prototype = bar;

    return f_;
}(); 

var obj = new foo();

alert(obj.a + ', ' + obj.b.d.e)

Note, () at the end of the foo function, those parentesis make foo execute immediately and assign new function f_ to it.

Upvotes: 1

Related Questions