Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'return' when creating objects with 'new'

Tags:

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:

  1. The newly-created "object" is instead a function.
  2. That new function can be invoked like normal, however...
  3. If you maintain a reference to this in the constructor function, this references an object that was correctly created from the constructor. It's what you expected to be returned from new.

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:

  1. 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?
  2. What happens in the background that causes this behavior?
  3. (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?