The ‘this’ keyword in javascript, part I (a riddle)

19 Oct

JavaScript is weird.

There! I’ve said it!
It might have something to do with the fact that the whole language was put together in about ten days..  In spite of that, it’s a powerful language in which you can do marvelous stuff.  Stuff some languages (Java(tm) to name just one) can only dream of :  closures, memoization, object literals, and last but certainly not least, a mass presence on the web – applet anyone?

But at the same time it’s a very confusing language, often lacking consistency . The behaviour of the [this] keyword is one of the key victims.

If you think you are on top of the [this] keyword, following riddle will probably not surprise you. But than again, it just might.

What’s the output of following script ?

var obj = {
    myValue: 10,
    this_1: this,
    this_2: function() {
        return this;
    this_3: (function() {
        return this;

myValue = 1000;

obj_this_2_ref = obj.this_2; // references the function obj.this2

this.myValue += 1;
obj.this_1.myValue += 1;
obj.this_2().myValue += 1;
obj_this_2_ref().myValue += 1;
obj.this_3.myValue += 1;

document.writeln(myValue + " ; " + obj.myValue);

The result that can be found here is in my opinion at least a little revolting…

The good news is that, even if the use of [this] might follow a strange kind of logic, logic it is.  And even more good news : once understood, this logic is fairly simple.

To be continued.