JavaScript on the server side is a wonderful tool for simple asynchronous jobs that take the most of the server you run. But if you come from a PHP background, you may quickly have strange bugs when writing object-oriented code in JavaScript.
Here is a simple script:
var A = function() { this.value = 'hello'; }; A.prototype.getValue = function() { return this.value; } var B = function() {} B.prototype.doStuff = function(callback) { return callback(); } var a = new A(); console.log(a.getValue()); // hello world var b = new B(); console.log(b.doStuff(a.getValue)); // undefined
What? b.doStuff()
takes a cllback as an argument and simply calls it, so the last line should return just the same string as the first call ('hello world').
It turns out the this
keyword in the getValue
function doesn't carry the same object in the two cases. That's right: in JavaScript, this
called from inside an object method yields a different result depending on how you call the method.
You will find all the details in these enlightening posts:
Bottomline: each time you pass a callback as an argument to another function, if this callback makes use of the this
keyword, uou must bind the callback to the object you want this
to refer to:
var b = new B(); console.log(b.doStuff(a.getValue.bind(a))); // hello world
I musn't be the first to fall into that pit, so hopefully this oddity of JavaScript won't surprise you too much.
Tweet
Published on 10 Jan 2012
with tags JavaScript