Hacker News new | ask | show | jobs
by vog 4209 days ago
The "this" keyword in JavaScript is a well-known anti-pattern. Although it can be explained with a few rules, it becomes cumbersome quickly.

The anti-pattern around "this" is well-known for decades. For example, SICP explicitly mentions that anti-pattern. Of course, it doesn't refer to JavaScript, but to some other old programming language which had a keyword with very similar issues. I think it's not a hyperbole to say that in this regard, the JavaScript/ECMAscript language designers haven't learned from the past.

The main issue is that "this" violates lexical context. Fortunately, the lexical context is easily restored by declaring a normal variable, usually named "me", and using the fact that variables have always lexical scope in JavaScript (as it should be):

    var me = this;
    someFunctionWithCallback(function() {
        me.something(...);
    });
Another workaround is adding a "scope" argument to functions which take callbacks:

    someFunctionWithCallback(function() {
        this.something(...);
    }, this);
Or:

    someFunctionWithCallback({
        callback: function() {
            this.something(...);
        },
        scope: this
    });
3 comments

As a side note, the relevant SICP lecture is 7B, second part, starting at 0:18:20.

https://www.youtube.com/watch?v=t5EI5fXX8K0&list=PLB63C06FAF...

es6 arrow functions preserve the lexical context for this, alternatively you can bind functions to the current this so it remains the same as the outer function scope.

strict mode + arrow functions bring a little more sanity to JS.

What? No, it's not an anti-pattern. It's about understanding functional scoping, JavaScript doesn't use lexical scoping.
Not sure where you got this from. JavaScript does use lexical scoping for almost everything, except for "this".
Yeah, that's what I meant, but it was before caffeine this morning and now its too late to edit.