lampShade
lampShade

Reputation: 4391

Why does this coffeescript blow up with the following error

Person = (name, age, job) ->
  @name = name
  @age = age
  @job = job
  @sayName = ->
    console.log(@name)

kim = new Person("Kimothy Lozado", 37, "Skip Tracer")


console.log kim.sayName()

Returned Error

TypeError: Object function () {
      return console.log(this.name);
    } has no method 'sayName'
  at Object.<anonymous> (/Users/aero/Downloads/m.coffee:11:17)
  at Object.<anonymous> (/Users/aero/Downloads/m.coffee:1:1)
  at Module._compile (module.js:456:26)

Upvotes: 1

Views: 44

Answers (2)

Ilan Frumer
Ilan Frumer

Reputation: 32367

I recommend agconti answer for creating classes, but here I want to answer to why this error occurs.

When you write a constructor in javascript:

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

var someone = new Person('someone');

The variable someone is assigned to the returned object of the new keyword.

But if the constructor returns a function:

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

var someone = new Person('someone');

Unfortunately, instead of getting the new created object, someone is assigned to the function returned by the constructor.

If we look at the compiled code of your coffee:

Person = function(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  return this.sayName = function() {
    return console.log(this.name);
  };
};

We see that the constructor returns a function. this happens because coffescript always returns the last expression of a function.

You can fix it by returning nothing:

Person = (name, age, job) ->
  @name = name
  @age = age
  @job = job
  @sayName = ->
    console.log(@name)
  return

Upvotes: 1

agconti
agconti

Reputation: 18093

Your not quite defining classes properly. Namely you need a constructor and need to use :s instead of =s unlike regular js.

Do this instead:

class Person
  constructor: (@name, @age, @job) ->

  sayName: ->
    console.log(@name)

kim = new Person("Kimothy Lozado", 37, "Skip Tracer")


console.log kim.sayName()

Demo in a fiddle : http://jsfiddle.net/4e8xZ/

Here's a great article on CoffeeScript class from the little book of CoffeeScript for your reference.

Upvotes: 2

Related Questions