Created
December 5, 2012 11:32
-
-
Save mainiak/4214899 to your computer and use it in GitHub Desktop.
nodejs setInterval and setTimeout doesn't persist scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/coffee | |
### | |
node v0.8.15 | |
### | |
# this doesn't work for setInterval either | |
class Test | |
constructor: (@text) -> | |
delay: 2000 | |
print: -> console.log @text | |
shouldWork: -> setTimeout @print, @delay | |
shouldWorkClosure: -> | |
obj = @ # closure | |
setTimeout obj.print, @delay | |
workingClosure: -> | |
obj = @ # closure | |
func = -> | |
obj.print() | |
setTimeout func, @delay | |
test = new Test 'dummy text' | |
test.print() # prints text | |
test.shouldWork() # undefined | |
test.shouldWorkClosure() # undefined | |
test.workingClosure() # prints text |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generated by CoffeeScript 1.4.0 | |
/* | |
node v0.8.15 | |
*/ | |
var Test, test; | |
Test = (function() { | |
function Test(text) { | |
this.text = text; | |
} | |
Test.prototype.delay = 2000; | |
Test.prototype.print = function() { | |
return console.log(this.text); | |
}; | |
Test.prototype.shouldWork = function() { | |
return setTimeout(this.print, this.delay); | |
}; | |
Test.prototype.shouldWorkClosure = function() { | |
var obj; | |
obj = this; | |
return setTimeout(obj.print, this.delay); | |
}; | |
Test.prototype.workingClosure = function() { | |
var func, obj; | |
obj = this; | |
func = function() { | |
return obj.print(); | |
}; | |
return setTimeout(func, this.delay); | |
}; | |
return Test; | |
})(); | |
test = new Test('dummy text'); | |
test.print(); | |
test.shouldWork(); | |
test.shouldWorkClosure(); | |
test.workingClosure(); |
I was expecting 'this' would be function I am passing to setTimeout - but it isn't. Still I have learned new thing today - so thank you Isaac for your response. :)
Ok, so it is really known issue :-/ https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let me introduce you to my little friend
Function.prototype.bind
.This is a general question about the value of
this
in JavaScript. Has nothing to do with Node or setTimeout in particular.