为什么 CoffeeScript 将类定义包装在闭包中?

2022-01-24 00:00:00 javascript minify coffeescript

在 CoffeeScript 中,这个:

In CoffeeScript, this:

class Foo
  method: (x) ->
    x+1

编译为:

// Generated By CoffeeScript
Foo = (function() {
  function Foo() {}
  Foo.prototype.method = function(x) {
    return x+1;
  }
  return Foo;
})()

这似乎有点过分了.以下内容应功能相同:

Which seems a bit excessive. The following should be functionally identical:

// Generated by Dave
function Foo() {}
Foo.prototype.method = function(x) {
    return x+1;
}

额外的闭包"包装器的动机是什么?

这不仅仅是样式问题.它对整体代码大小有影响.

This is not merely an idle question of styling; it has implication to overall code size.

Coffee 版本缩小为 84 个字节:

The Coffee version minifies into 84 bytes:

Foo=function(){function e(){}return e.prototype.method=function(e){return e+1},e}();

我的版本缩小到只有 61 个字节:

My version minifies into only 61 bytes:

function Foo(){}Foo.prototype.method=function(e){return e+1};

23 字节是愚蠢的无关紧要,但在一个有很多类的项目中,开销开始增加.

好的,我在下面写了一个反驳字节大小理论的答案......对于任何合理的类,Coffee 方法都会更小.

Ok, I wrote an answer below refuting the byte size theory ... for any reasonable class, the Coffee method is going to be smaller.

可能还有其他原因.帮我想想它们.

There's probably other reasons too. Help me think of them.

推荐答案

Jeremy 在相关问题中回答了这个问题 -看起来主要目的是避免触发 IE 错误.

Jeremy answers this over in a related question - it looks like the primary intent is to avoid triggering an IE bug.

相关文章