Archive

Archive for April, 2012

Don’t use this in JavaScript

April 28, 2012 8 comments

this JavaScript:

var o = {
    f1: function() {
        console.log('hi');
    },
    f2: function() {
        this.f1();
    }
};

o.f2.prototype.f1 = function() {
    console.log('bye');
}

var k = {
    f1: function() {
        console.log('pfff');
    }
}

new o.f2();
o.f2.apply(k);
o.f2();
var x = o.f2;
x();

There. That’s why I never use the this keyword in JavaScript.
And that’s why I think you should stop using it too.
Can you figure out what’s the output of this code?

Read more…