2

I'm learning CoffeeScript I have this code:

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

And is generating this javascript code:

// 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);

I want to create instances of that class, but since it's inside the closure I can't how should I do that?

Pablo
  • 8,001
  • 13
  • 50
  • 74

2 Answers2

1

An option that is slightly less hackish is the @ operator (which is the same as this). In a browser environment, this will point to window, in node.js, it will point to exports.

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

window.Person only works on the browser, the @ will work for node and the browser. See https://stackoverflow.com/a/24352630/227299

Alternatively, you can run coffescript with the -b (--bare) option and the wrapping function won't be created.

Community
  • 1
  • 1
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
0

change a bit declaration of a class

class window.Person
  constructor: (@firstName, @lastName) ->
  sayHi: () ->
    return "Hi, I'm #{@firstName} #{@lastName}"
djaszczurowski
  • 4,279
  • 1
  • 18
  • 27