I have the following CoffeeScript code example:
class TestClass
constructor: () ->
@list = new Object()
addToList: (key, value) ->
@list[key] = value
printList: () ->
console.log("This is printed from printList:", @list)
startHttp: () ->
http = require("http")
http.createServer(@printList).listen(8080)
test = new TestClass()
test.addToList("key", "value")
test.printList()
test.startHttp()
When I run the code, and make a HTTP request to 127.0.0.1:8080, I expect to get the following output:
This is printed from printList: { key: ‘value’ }
This is printed from printList: { key: ‘value’ }
But I get the following instead:
This is printed from printList: { key: ‘value’ }
This is printed from printList: undefined
Why is it the printList function can’t access the list variable when it is called from the HTTP server?
I am using Node.js v0.6.1 and CoffeeScript v1.1.3.
Use
=>to bind the value ofthisto the function so it “works” as you expect.Disclaimer: instances might break. Coffeescript is black magic for all I care.
What you really want to do is invoke the method on the correct object
Or in plain javascript.