为什么coffeescript生成这样的类? [英] Why does coffeescript generate classes like this?

查看:80
本文介绍了为什么coffeescript生成这样的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下coffeescript代码:

Given the following coffeescript code:

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;
})();

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

But why isn't this more idiomatic code generated?

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

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

I know that coffeescript wraps a lot of stuff in anonymous functions to control scope leak, but what could leak here?

推荐答案

生成的代码可以在Internet Explorer中可靠地命名函数。 (在这种情况下,为Animal。)如果你只使用顶层作用域中的命名函数,它会与可能存在的任何 var Animal = 声明冲突。即使在较低的范围,阻止它们被正确引用。要解决IE错误,我们在类定义周围添加函数包装。

The generated code makes it possible to reliably have named functions in Internet Explorer. (In this case, "Animal".) If you simply use a named function at top-level scope, it will conflict with any var Animal = declarations that might be present ... even in lower scopes, preventing them from being referenced correctly. To work around the IE bug, we include the function wrapper around the class definition.

这篇关于为什么coffeescript生成这样的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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