1

I'm confused by a javascript design pattern I'm reading about:

var class = (function() {

  ...a bunch of code...

  return {

  .. some more code..

  ;

  // or, in some cases

  return function(constructorArgs) {

  };

})();

My question is: What is the return statement doing? Why is it there? I'm confused because no-one wants to mention it or talk about it.

4
  • Do you know what the () in the last line does? Commented Jan 20, 2013 at 22:23
  • The return statement returns from the function it's in (what did you expect it to do?). Commented Jan 20, 2013 at 22:25
  • No. I still don't understand. Commented Jan 20, 2013 at 22:26
  • @JaPerk14 Start here: stackoverflow.com/questions/8228281/… Commented Jan 20, 2013 at 22:28

4 Answers 4

3

There's two distinct patterns that you're mentioning, I think.

Anonymous Closures

The first is using an anonymous function to wrap a block of code in order to create a closure:

var outer = (function() {
  var inner = "now you see me!";

  return inner + " now you don't"
})()

The anonymous function creates a new scope for var-defined variables. In effect, this allows you to define variables that are only visible within that particular function.

In the example above, you have access to inner within the function, but it is not defined outside of it.

"Classes"

The second is a common pattern for defining "classes" in JavaScript:

var MyClass = (function() {
  function MyClass(arg) {
    this.arg = arg
  }

  return MyClass
})()

By defining the constructor function within a closure, you can be sure that your class is well contained. It also enables you to share class-wide state or private helper methods without polluting the global namespace, or resorting to placing them as properties on your class constructor's prototype.

Sign up to request clarification or add additional context in comments.

5 Comments

Wow. Someone's pretty trigger-happy with the old down-vote button. +1 for a good explanation of classes - I couldn't find the words.
I'm downvoting every answer that contains an incorrect explanation of "closure". Using an anonymous function that wraps a block of code is not a closure; it's just an anonymous function. The MyClass example doesn't involve a closure either. A closure is a function that refers to external local variables, i.e. variables from a surrounding scope.
en.wikipedia.org/wiki/Closure_(computer_science) - a lexical closure is independent from a function; it just happens that in JavaScript, functions define lexical closures within their bodies.
The code executed within the block of any JS function is being executed within a new closure. It may not be referencing variables defined (lexically) outside of the closure's immediate scope - but that does not make the function body any less of a closure.
next time, rather than downvote every explanation you don't like, try to write your own. Cheers.
2

the code to the right of the = symbol is of this form: (function(){})(); What this does is compile a function - effectively the same as the following:

function temp() {
}

class = temp();

Inside the function in your example, however, there is another function being returned. What this means is that class is now also a function - the class function can then reference all of the variables etc. that are declared in the temp function, due to the closure effect referenced by vtortola.

The idea of this is to allow the inner function to refer to some state that you don't want to have hanging around in your "global" (or semi-global) scope - it doesn't matter where the class method is called, or who by, it will always have access to that data.

Edit: It appears from the code that the purpose of the pattern in this case is to create a "class" type function - so then you'd be able to call it with the following code:

var myInstance = new class();

Though I've a feeling that none of the code will work as I'm reasonably certain that class is a reserved word...

Comments

2

This is called a closure.

var myVar = (function (param1, param2){
    //do things
}('myParam1','myParam2')):

The javascript engine will immediatly execute what is between the parenthesis.

And the value of myVar will be what the function function (param1, param2){ ... } returns.

This function will use ('myParam1','myParam2') as arguments.

You can write closure in two different ways :

(function (receivedArgs){
  //do things
})(yourArguments);

or

(function (receivedArgs){
   //do things
}(yourArguments));

Comments

1

It is a closure. A function is returning an inner function enclosing some variables in the middle.

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures

Cheers.

Comments

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.