2 ms·
My take is that `this` is fine and straightforward as long as you follow a few rules: 1.) `this` should only be used inside a class method. 2.) Never use `som
by alangpierce 8y ago
My take is that `this` is fine and straightforward as long as you follow a few rules:
1.) `this` should only be used inside a class method.
2.) Never use `someClassInstance.someMethod` as a value (invoking it is ok, but accessing it without invoking it isn't). Make it a bound method using class field syntax or wrap it in an arrow function and invoke it there.
3.) Never use `function` syntax for function expressions (e.g. callbacks), only arrow functions. Callbacks should never need `this` because the information they need should be provided via arguments.
Fortunately, modern tools make this pretty easy to follow. #1 is mostly enforced naturally by TypeScript; if you try using `this` in a plain function, it will yell at you unless you explicitly annotate what `this` means. #2 is enforced by the TSLint rule no-unbound-method. #3 is enforced by the ESLint rule prefer-arrow-callback. With these rules, even beginners on my team have rarely/never made `this`-related JS mistakes.