为什么CoffeeScript在闭包中包装类定义? [英] Why does CoffeeScript wrap class definitions in a closure?

查看:225
本文介绍了为什么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;
}

额外的closure包装的动机是什么? / strong>

What is the motivation for the extra "closure" wrapper?

这不仅仅是一个空白的样式问题;

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.

这篇关于为什么CoffeeScript在闭包中包装类定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆