deno.com

no-this-alias

注意: 此规则是 recommended 规则集的一部分。
deno.json 中启用完整规则集
{
  "lint": {
    "tags": ["recommended"]
  }
}
使用 Deno CLI 启用完整规则集
deno lint --tags=recommended

禁止将变量赋值给 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;

您找到您需要的内容了吗?

隐私政策