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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top