7

给定以下咖啡脚本代码:

class Animal
  constructor: (@name) ->
  speak: (things) -> "My name is #{@name} and I like #{things}"

这是生成的:

var Animal = (function() {
  function Animal(name) {
    this.name = name;
  }
  Animal.prototype.speak = function(things) {
    return "My name is " + this.name + " and I like " + things;
  };
  return Animal;
})();

但是为什么不生成更惯用的代码呢?

var Animal = function Animal(name) {
  this.name = name;
};
Animal.prototype.speak = function(things) {
  return "My name is " + this.name + " and I like " + things;
};

我知道coffeescript 在匿名函数中包装了很多东西来控制范围泄漏,但是这里可能会泄漏什么?

4

3 回答 3

12

生成的代码可以在 Internet Explorer 中可靠地使用命名函数。(在这种情况下,“Animal”。)如果您只是在顶级范围内使用命名函数,它将与var Animal =可能存在的任何声明冲突......即使在较低范围内,也会阻止它们被正确引用。为了解决 IE 错误,我们在类定义周围包含函数包装器。

于 2011-01-12T17:51:54.747 回答
2

这是为了支持回溯,包括类名,而不仅仅是抛出异常时的函数名。

于 2011-01-12T16:34:12.743 回答
2

CoffeeScript 方法还具有缩小的优势。

我的另一个答案

对于大多数合理的类,CoffeeScript 生成的闭包会生成更小的缩小输出。 闭包包装器减少了 25 个字节的开销,但它使您免于重复 classname,节省k * N字节(k=letters-in-name,N=num-of-refs)。例如,如果一个类似的类BoilerPlateThingyFactory有 2 个以上的方法,则闭包包装器会生成更小的压缩代码。



更详细...

Coffee 使用闭包生成的代码缩小为:

// Uglify '1.js' = 138 bytes (197 w/ whitespace):

var Animal=function(){function e(e){this.name=e}return e.prototype.speak=function(e){return"My name is "+this.name+" and I like "+e},e}();

// with whitespace ("uglifyjs -b"):

var Animal = function() {
    function e(e) {
        this.name = e;
    }
    return e.prototype.speak = function(e) {
        return "My name is " + this.name + " and I like " + e;
    }, e;
}();

ryeguy 的替代“惯用”实现缩小到这一点:

// Uglify '2.js' = 119 bytes (150 w/ whitespace):

var Animal=function(t){this.name=t};Animal.prototype.speak=function(e){return"My name is "+this.name+" and I like "+e};

// with whitespace ("uglifyjs -b"):

var Animal = function(t) {
    this.name = t;
};

Animal.prototype.speak = function(e) {
    return "My name is " + this.name + " and I like " + e;
};

请注意名称“动物”名称在 Coffee 形式中恰好存在一次,而在 ryeguy 的“惯用”变体中 N=2 次。现在“Animal”只有 6 个字母,而且只有 1 个方法,所以这里的 Coffee 应该会丢失 25-6 = 19 个字节。咨询我的缩小代码,它是 138 字节到 119 字节,增量为 ... 19 字节。再增加4个方法,优势会切换到Coffee。这不仅仅是方法;类常量和其他 ref 类型也很重要。

于 2012-08-18T01:45:52.760 回答