Skip to content

Instantly share code, notes, and snippets.

@mainiak
Created December 5, 2012 11:32
Show Gist options
  • Save mainiak/4214899 to your computer and use it in GitHub Desktop.
Save mainiak/4214899 to your computer and use it in GitHub Desktop.
nodejs setInterval and setTimeout doesn't persist scope
#!/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
// 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();
@isaacs
Copy link

isaacs commented Dec 8, 2012

Let me introduce you to my little friend Function.prototype.bind.

   Test.prototype.shouldWork = function() {
-    return setTimeout(this.print, this.delay);
+    return setTimeout(this.print.bind(this), this.delay);
   };
   Test.prototype.shouldWorkClosure = function() {
      var obj;
      obj = this;
-    return setTimeout(obj.print, this.delay);
+    return setTimeout(obj.print.bind(this), this.delay);
   };

This is a general question about the value of this in JavaScript. Has nothing to do with Node or setTimeout in particular.

@mainiak
Copy link
Author

mainiak commented Jan 2, 2013

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. :)

@mainiak
Copy link
Author

mainiak commented Jan 2, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment