| 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
});
|
https://www.youtube.com/watch?v=t5EI5fXX8K0&list=PLB63C06FAF...