JS.TS.NO.THIS.ALIAS

Disallow aliasing 'this'

This rule prohibits assigning variables to this.

Rule Details

Assigning a variable to this instead of properly using arrow lambdas may be a symptom of pre-ES6 practices or not managing scope well.

Instead of storing a reference to this and using it inside a function () {:

Copy
const self = this;
>
setTimeout(function () {
    self.doWork();
});

Use () => arrow lambdas, as they preserve this scope for you:

Copy
setTimeout(() => {
  this.doWork();
});

Examples of incorrect code for this rule:

(see the rationale above)

Examples of correct code for this rule:

(see the rationale above)

Options

You can pass an object option:

Copy
{
  "@typescript-eslint/no-this-alias": [
    "error",
    {
      "allowDestructuring": false, // Disallow `const { props, state } = this`; true by default
      "allowedNames": ["self"] // Allow `const self = this`; `[]` by default
    }
  ]
}

When Not To Use It

If you need to assign this to variables, you shouldn’t use this rule.

The content on this page is adapted from the ESLint User Guide. Copyright © OpenJS Foundation and other contributors, www.openjsf.org. All rights reserved. https://eslint.org/docs/rules/