no-this-alias
Disallow aliasing
this
.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended"
可启用此规则。
将变量分配给 this
而不是正确使用箭头 lambda 可能是 ES6 之前的实践或没有很好地管理范围的症状。
英:Assigning a variable to this
instead of properly using arrow lambdas may be a symptom of pre-ES6 practices
or not managing scope well.
module.exports = {
"rules": {
"@typescript-eslint/no-this-alias": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
const self = this;
setTimeout(function () {
self.doWork();
});
Open in PlaygroundsetTimeout(() => {
this.doWork();
});
Open in Playground选项
allowDestructuring
有时,从类实例中解构属性可能很有用,例如在其方法之一中从实例中检索多个属性。
allowDestructuring
允许这些解构,并且默认为 true
。
你可以通过将 allowDestructuring
设置为 false
来明确禁止它们。
英:It can sometimes be useful to destructure properties from a class instance, such as retrieving multiple properties from the instance in one of its methods.
allowDestructuring
allows those destructures and is true
by default.
You can explicitly disallow them by setting allowDestructuring
to false
.
{ "allowDestructuring": false }
选项的代码示例:
英:Examples of code for the { "allowDestructuring": false }
option:
- ❌ 不正确
- ✅ 正确
class ComponentLike {
props: unknown;
state: unknown;
render() {
const { props, state } = this;
console.log(props);
console.log(state);
}
}
Open in Playgroundclass ComponentLike {
props: unknown;
state: unknown;
render() {
console.log(this.props);
console.log(this.state);
}
}
Open in PlaygroundallowedNames
no-this-alias
也可以用于仅允许特定名称列表作为 this
别名。
我们建议不要这样做,除非作为解决所有违规行为的临时步骤。
英:no-this-alias
can alternately be used to allow only a specific list of names as this
aliases.
We recommend against this except as a transitory step towards fixing all rule violations.
{ "allowedNames": ["self"] }
选项的代码示例:
英:Examples of code for the { "allowedNames": ["self"] }
option:
- ❌ 不正确
- ✅ 正确
class Example {
method() {
const that = this;
}
}
Open in Playgroundclass Example {
method() {
const self = this;
}
}
Open in Playground何时不使用它
如果你的项目的结构需要将 this
分配给变量,则此规则可能不适合你。
如果只有项目的一个子集将 this
分配给变量,那么你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
英:If your project is structured in a way that it needs to assign this
to variables, this rule is likely not for you.
If only a subset of your project assigns this
to variables then you might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
选项
该规则接受以下选项
type Options = [
{
/** Whether to ignore destructurings, such as `const { props, state } = this`. */
allowDestructuring?: boolean;
/** Names to ignore, such as ["self"] for `const self = this;`. */
allowedNames?: string[];
},
];
const defaultOptions: Options = [
{ allowDestructuring: true, allowedNames: [] },
];