deno.com

禁止 this 别名

注意:此规则是 recommended 规则集的一部分。
deno.json 中启用完整集合
{
  "lint": {
    "rules": {
      "tags": ["recommended"]
    }
  }
}
使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
通过将其添加到 deno.json 中的 includeexclude 数组中,可以将此规则明确地包含或排除在当前标签中的规则之外
{
  "lint": {
    "rules": {
      "include": ["no-this-alias"],
      "exclude": ["no-this-alias"]
    }
  }
}

禁止将变量赋值给 this

在大多数情况下,通过正确使用箭头函数可以避免将 this 的引用存储在变量中,因为箭头函数是根据其定义所在的作用域来确定 this 的。

我们来看一个具体示例

const obj = {
  count: 0,
  doSomethingLater() {
    setTimeout(function () { // this function executes on the global scope; `this` evalutes to `globalThis`
      this.count++;
      console.log(this.count);
    }, 300);
  },
};

obj.doSomethingLater();
// `NaN` is printed, because the property `count` is not in the global scope.

在上面的示例中,传递给 setTimeout 的函数中的 this 求值为 globalThis,导致预期的值 1 未被打印。

如果你想在不使用箭头函数的情况下解决这个问题,你需要将 this 的引用存储在另一个变量中

const obj = {
  count: 0,
  doSomethingLater() {
    const self = this; // store a reference to `this` in `self`
    setTimeout(function () {
      // use `self` instead of `this`
      self.count++;
      console.log(self.count);
    }, 300);
  },
};

obj.doSomethingLater();
// `1` is printed as expected

但在这种情况下,箭头函数就派上用场了。使用箭头函数,代码变得更加清晰易懂

const obj = {
  count: 0,
  doSomethingLater() {
    setTimeout(() => { // pass an arrow function
      // `this` evaluates to `obj` here
      this.count++;
      console.log(this.count);
    }, 300);
  },
};

obj.doSomethingLater();
// `1` is printed as expected

此示例摘自 MDN

无效示例

const self = this;

function foo() {
  const self = this;
}

const bar = () => {
  const self = this;
};

有效示例

const self = "this";

const [foo] = this;

您找到所需内容了吗?

隐私政策