3 ms·
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 a
by vog 12y 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
});
- the8472 12y agoes6 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.
- ulisesrmzroche 12y agoWhat? No, it's not an anti-pattern. It's about understanding functional scoping, JavaScript doesn't use lexical scoping.
- vog 12y agoNot sure where you got this from. JavaScript does use lexical scoping for almost everything, except for "this".
- deleted 12y ago[deleted]
- ulisesrmzroche 12y agoYeah, that's what I meant, but it was before caffeine this morning and now its too late to edit.
- vog 12y agoAs a side note, the relevant SICP lecture is 7B, second part, starting at 0:18:20. https://www.youtube.com/watch?v=t5EI5fXX8K0&list=PLB63C06FAF154F047#t=1100 https://www.youtube.com/watch?v=t5EI5fXX8K0&list=PLB63C06FAF...