Question

I have defined the following piece of Coffeescript code below, which defines a function using RequireJS:

define 'PersonService', ['jquery'] ($) -> 
    getPerson = (id) -> 
        person = dataService.GetPerson id
    { getPerson: getPerson}

It produces the following:

(function() {

  define('PersonService', ['jquery'](function($) {
    var getPerson;
    getPerson = function(id) {
      var person;
      return person = dataService.GetPerson(id);
    };
    return {
      getPerson: getPerson
    };
  }));

}).call(this);

I guess the issue I have is with the self-executing function that is produced from the Coffeescript code. Will this cause issues that I am possibly not tracking? Or is this proper.

Thank you.

Was it helpful?

Solution

It's correct

The difference between not having a wrapped function and having one is to do with scope.

If you define var a = 10; in the global scope a becomes global with or without the var keyword.

When wrapped all variables are local to the wrapped function so do not end up global.

In you example everything is already wrapped in a function so yes you don't need the extra wrapping!

You can tell coffee-script not to add the wrapper function using

coffee -b, --bare         compile without a top-level function wrapper

IMHO: It's better to always have the wrapper function so you don't need to think about it on a file to file basis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top