close

no-this-outside-of-class

Unreleased

Configuration

PresetConfigured Value
✅ unicornPlugin.configs.recommended"error"
rslint.config.ts
import { defineConfig, unicornPlugin } from '@rslint/core';

export default defineConfig([
  unicornPlugin.configs.recommended,
  {
    rules: {
      'unicorn/no-this-outside-of-class': 'error',
    },
  },
]);

Rule Details

Disallow this outside of classes. this should only be used when JavaScript class syntax or an explicit TypeScript this parameter defines the receiver.

Examples of incorrect code for this rule:

function Foo(value) {
  this.value = value;
}

const foo = {
  method() {
    return this.value;
  },
};

Foo.prototype.method = function () {
  this.value();
};

class Foo {
  method() {
    function getValue() {
      return this.value;
    }

    return getValue();
  }
}

Examples of correct code for this rule:

class Foo {
  constructor(value) {
    this.value = value;
  }

  method() {
    return this.value;
  }
}

class Foo {
  method() {
    const getValue = () => this.value;
    return getValue();
  }
}

const foo = {
  validator(this: TrackedModel) {
    return this.value;
  },
};

Original Documentation