【问题标题】:Proper use of RequireJS, Coffeescript and Revealing Module Pattern正确使用 RequireJS、Coffeescript 和 Revealing Module Pattern
【发布时间】:2012-09-04 14:49:00
【问题描述】:

我在下面定义了一段 Coffeescript 代码,它使用 RequireJS 定义了一个函数:

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

它产生以下内容:

(function() {

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

}).call(this);

我想我遇到的问题是由 Coffeescript 代码生成的自执行函数。这会导致我可能无法跟踪的问题吗?或者这样合适吗?

谢谢。

【问题讨论】:

    标签: javascript coffeescript requirejs amd revealing-module-pattern


    【解决方案1】:

    没错

    没有封装函数和有封装函数的区别在于范围。

    如果你定义 var a = 10;在全局范围内,无论有无 var 关键字,a 都变为全局。

    包装后,所有变量都是被包装函数的本地变量,因此不要最终成为全局变量。

    在您的示例中,所有内容都已包装在一个函数中,所以是的,您不需要额外的包装!

    你可以告诉coffee-script不要使用

    添加包装函数
    coffee -b, --bare         compile without a top-level function wrapper
    

    恕我直言:最好始终拥有包装器功能,这样您就无需逐个文件考虑它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2012-11-12
      • 1970-01-01
      • 2013-10-14
      相关资源
      最近更新 更多