为什么coffescript会创建这个闭包

时间:2016-01-21 19:04:53

标签: javascript coffeescript

我正在学习CoffeeScript我有这段代码:

class Person
    constructor: (@firstName, @lastName) ->
    sayHi: () ->
        return "Hi, I'm #{@firstName} #{@lastName}"

正在生成此javascript代码:

// Generated by CoffeeScript 1.10.0
(function() {
  var Person;

  Person = (function() {
    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }

    Person.prototype.sayHi = function() {
      return "Hi, I'm " + this.firstName + " " + this.lastName;
    };

    return Person;

  })();

}).call(this);

我想创建class的实例,但由于它在封闭内部,我不能怎么做?

2 个答案:

答案 0 :(得分:1)

@运算符(与this相同)的选项稍微不那么严重。在浏览器环境中,this将指向window,在node.js中,它将指向exports

class @Person
  constructor: (@firstName, @lastName) ->
  sayHi: () ->
    return "Hi, I'm #{@firstName} #{@lastName}"

window.Person仅适用于浏览器,@适用于节点和浏览器。见https://stackoverflow.com/a/24352630/227299

或者,您可以使用-b (--bare)选项运行coffescript,并且不会创建包装函数。

答案 1 :(得分:0)

更改类的位声明

class window.Person
  constructor: (@firstName, @lastName) ->
  sayHi: () ->
    return "Hi, I'm #{@firstName} #{@lastName}"