Reputation: 4391
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()
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
Reputation: 32367
I recommend agconti answer for creating classes, but here I want to answer to why this error occurs.
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.
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.
Person = (name, age, job) ->
@name = name
@age = age
@job = job
@sayName = ->
console.log(@name)
return
Upvotes: 1
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