10

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?
Kevin McTigue
  • 3,503
  • 2
  • 18
  • 22

3 Answers3

7
  1. 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.

  2. See #1

  3. This is because a function creates a closure, so it continues to reference the self variable, 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.

function Constructor() {

  this.name = 'instance';
  return [ this ];  // Instead return an Array that references the new object
}
  • I see! So the variable "instance" in my example is a *closure*, not a normal function? And that closure contains both the returned function AND instantiated object, which can be accessed with "this"? – Kevin McTigue Feb 16 '12 at 01:50
  • 2
    @KevinMcTigue: Well, all functions are closures. It's simply part of the internal implementation of functions in JavaScript. What makes a function a closure is that it has a permanent reference to the original variable scope where it was created. So you're just returning a plain old function, which is behaving properly like any other function, in that it doesn't lose sight of its variable scope *(which includes the `self` variable, which references your new object)*. –  Feb 16 '12 at 01:54
2

Well, that is a really good question and, as you may have guessed, not easily answered.

To put it very simply:
1) Yes and Yes; this is one of the amazing features you don't find in "traditional" programming languages.
2) please read about closures (links below)
3) Yes (please read more)

You should read more about Javascript Closures: http://jibbering.com/faq/notes/closures/
http://www.javascriptkit.com/javatutors/closures.shtml (here you got some good working examples)

and, more particularly, the Parasitic Inheritance model:
http://blog.higher-order.net/2008/02/21/javascript-parasitic-inheritance-power-constructors-and-instanceof/

I hope this helps

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
1

this is what you call a closure

what it does is create a self-contained code environment (commonly known as an object)

typeof instance    //returns "function" - since it's not "fired" or called. just returns the function declaration (correct me if i'm wrong)
typeof instance()  //returns "object" - it returns an object since you called it
instance()         //returns an object also - you called it, but you didn't store it

an example of an object built using a closure:

function Constructor() {
    var privateProperty = 'private';
    var privateMethod = function(){
        alert('called from public method');
    };

    //return only what's to be seen in public
    return {
        publicProperty: 'im public',
        publicMethod: function(){
            alert('called from public method');
        }
        getter: privateMethod //assign to call the private method
    }
}

var myObj = Constructor();
var pubProp = myObj.publicProperty; // pubProp = 'im public'
myObj.publicMethod()                //alert: 'called from public method';
myObj.getter()                      //alert: 'called from public method';

//cannot access since "private":
myObj.privateProperty
myObj.privateMethod
Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    _"what it does is create a self-contained code environment (commonly known as an object)"_ - Commonly known as a "closure". It's not an "object", at least not in the sense of being a JS object. Also, if your function explicitly returns an object it is not a good practice to call it with `new` because that is misleading - if using `new` you'd expect the result to be an instance of `Constructor`. – nnnnnn Feb 16 '12 at 01:42
  • According to the MDN page on closures: *"A closure is a special kind of object that combines two things: a function, and the environment in which that function was created."* – Kevin McTigue Feb 16 '12 at 01:46
  • 1
    @nnnnnn i just explained in simple terms. although it's not anobject, it's common use it to emulate an object (having private and public properties). as for the `new`.. i didn't know about that. – Joseph Feb 16 '12 at 01:51
  • 3
    @KevinMcTigue: The *"special kind of object"* MDN talks about is more of an internal implementation detail. The function object *(which we can reference)* has an internal reference to an object *(that we can not directly reference)* that records information about its variable environment (including a reference to its enclosing environment). This internal reference is permanent, which is what allows the function to always reference the variables in its original scope. –  Feb 16 '12 at 02:01
  • That's very interesting. When I was first learning js I sort of skimmed over closures as "they maintain a link back to their original scope" which is true, but a little more complex than that. – Kevin McTigue Feb 16 '12 at 02:02
  • @Joseph thanks for the answer and thorough code. This deserves an upvote. – Kevin McTigue Feb 16 '12 at 02:04