1

Why is it that I can't create an object from a function defined in a closure?

var outer = function() {
  var constructor = function() { 
    this.foo = 1; 
  }; 
  return constructor;
};

// Should be: { foo: 1 }, but is: undefined
var constructorObject = new outer()();

// This works
var c = outer();
var constructorObject = new c();    
2
  • 1
    The inner function doesn't return anything. Commented Oct 10, 2014 at 15:45
  • function doesn't return anything and sets foo on the context object... try this: var ctxt = {}; new outer().call(ctxt); console.log(ctxt.foo); Commented Oct 10, 2014 at 15:47

2 Answers 2

3

Because by calling ()() you get the inner function result. And as inner function doesn't have return statement it equals to undefined.

If you want to return object there your function should be like:

var inner = function() {
    return { foo: 1 };
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think the example is a bit misleading. I don't just want to nest functions, I want to return a constructor.
Further, if you want to create another new object, then break them up into separate lines: var outerObj = new outer(); var inner = new outerObj(); console.log(inner);
@tonekk so what do you expect to have in return? Object or constructor? Or what?
you can try to return return this; then constructorObject.foo will equal 1. This is what you want?
1

You need to wrap the outer function call in parenthesis like so:

var constructorObject = new (outer())();
//                          ^       ^ parenthesis here

console.log(constructorObject); // constructor {foo: 1} 
console.log(constructorObject.foo); // 1

1 Comment

Ah I get it! The new is applied to 'outer' instead of the return of 'outer' (which is 'constructor'). Tricky :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.