2

I'm working with the following:

define(["knockout"], function(ko) {

    var vm = this;

    (function() {    // I'm tempted to delete this
        // init
        vm.data = ko.observable("");
        // other stuff         

    })();  // and this

    return vm;
});

The person who wrote this said they thought it was a best practice but didn't know why. I understand this is a closure but we don't need any of the "private" functionality that closures provide in this instance, so this just seems like noise to me, but I'm probably overlooking something. What's the point?

BLAZORLOVER
  • 1,971
  • 2
  • 17
  • 27

1 Answers1

3

You will find a full explanation on that notation in answers to this question: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

Short version (sample of accepted answer):

What you're doing when you write (function() { ... code ... })(), is you're making the code inside a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()). So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:

> (function() {    var private_var;
> 
>    function private_function() {
>      //code    } })()
Community
  • 1
  • 1
GôTô
  • 7,974
  • 3
  • 32
  • 43
  • Thank you! If I'm already in a requireJS module with no need for further "inner" encapsulation, would this provide no benefit? – BLAZORLOVER May 14 '14 at 19:49
  • I think you can probably remove if you want. On the other hand do you really need to? – GôTô May 14 '14 at 19:53