I found something very odd today: If you create objects with a constructor function and the new keyword, but return a function from the constructor, it behaves like so:
- The newly-created “object” is instead a function.
- That new function can be invoked like normal, however…
- If you maintain a reference to
thisin the constructor function,thisreferences an object that was correctly created from the constructor. It’s what you expected to be returned fromnew.
Here’s an example:
function Constructor() {
var self = this;
this.name = 'instance';
return function() {
return self;
}
}
So if you instantiated it like this: var instance = new Constructor()
The following would result:
typeof instance //returns "function"
typeof instance() //returns "object"
instance() //returns { name: 'instance' }
So I guess I have three questions:
- Is this legal and does it work cross-browser? It’s really awesome and I think it can be used in a lot of ways, but is this behavior dependable?
- What happens in the background that causes this behavior?
- (maybe answered by 2, but…) Is the new object (the one referenced with ‘this’) inside the new instance, so that it’s all self-contained and is cleaned up properly by the garbage collector?
Yes, while a constructor by default returns the new object being constructed (which is referenced by
this), you can override that return value as long as you return an object. Because a function is an object, you can return it as you are in your example. The newly created object is not a function itself, but your returned function references the newly created object in its variable scope.See #1
This is because a function creates a closure, so it continues to reference the
selfvariable, which happens to reference the actual object being constructed. So I wouldn’t quite say it’s “inside” anything, but rather is simply part of the variable scope of the function.The thing to understand is that your function isn’t any different from any other function. Just like if you had instead returned an Array, you’d just have a regular Array, which could reference the new object.