简体   繁体   中英

CoffeeScript with Node.js not working with classes

I've a person.coffee file that contains the following code

class Person 
  constructor: (@name) ->
  talk: ->
    "hello"

module.exports = Person

Now I am trying to use it in app.js

Person = require "./person"
p = new Person "Emma"
console.log p.talk

It prints [Function] in the console. Any idea that what is wrong

Note: I've updated the spaces. Solution: I changed p.talk to p.talk() in app.js and its fixed now.

seems like your indent is broken, your code will compile to

var Person;

Person = (function() {

  Person.name = 'Person';

  function Person(name) {
    this.name = name;
    ({
      talk: function() {
        return "hello";
      }
    });
  }

  return Person;

})();

while you want something like this

class Person 
  constructor: (@name) ->

  talk: -> "hello"

which will be compiled into

var Person;

Person = (function() {

  Person.name = 'Person';

  function Person(name) {
    this.name = name;
  }

  Person.prototype.talk = function() {
    return "hello";
  };

  return Person;

})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM