I’m trying to create a module/class in node.js to measure asynchronous execution time but do not understand whats wrong with it. I created the following class “Measure.js”
var Measure = module.exports = function(param_timeout, param_cb) {
this.timeout = param_timeout;
this.cb = param_cb;
}
Measure.prototype = {
startDate: "0",
timeout:"0",
cb:null,
start : function() {
this.startDate = new Date();
console.log('started');
},
stop : function() {
var stopDate = new Date();
this.cb(null,(stopDate-this.startDate));
}
}
I use it with the following code:
var Measure = require('./Measure.js');
measure1 = new Measure(100,function(err,result){console.log('result: ' + result)});
measure1.start();
//do something
measure1.stop();
and it works just fine. However, if I try this:
var Measure = require('./Measure.js');
measure1 = new Measure(100,function(err,result){console.log('result: ' + result)});
measure1.start();
//do something
setTimeout(measure1.stop,100);
it doesn’t work and throws a TypeError:
TypeError: Object #<Object> has no method 'cb'
Whats wrong with my code?
When you directly call object’s method,
thisinside the method referred to your object, but when you try to use it as argument,thiswill referred to global object (globalorwindow).In your case better to replace
with
More about
thisbehavior: http://bonsaiden.github.com/JavaScript-Garden/#function.this