为什么要在tappable Hook类的构造函数中将类方法重新分配给`this`?

问题描述 投票:0回答:1

这是 webpack 可点击源代码中的代码:


class Hook {
  constructor(args = [], name = undefined) {
    this._args = args;
    // ...
    this.compile = this.compile;
    this.tap = this.tap;
    this.tapAsync = this.tapAsync;
    this.tapPromise = this.tapPromise;
  }
  // ...
  compile(options) {}

  tap(options, fn) {}

  tapAsync(options, fn) {}

  tapPromise(options, fn) {}
}

this.compile = this.compile
是什么意思,谁能告诉我吗?

webpack 可点击源代码链接

重新分配有什么魔力吗?

javascript class webpack
1个回答
0
投票

我已经在评论中回答过,这没有任何意义。什么都没有。然而,有趣的是,像

this.property = this.property
这样的赋值会执行以下两件事之一:将属性分配给
undefined
或不修改它。这取决于。

考虑一下:

class A {
    constructor () {
        // fooling around:
        this.a = this.a;
        this.b = this.b;
        console.log(`a: ${this.a}, b: ${this.b}`);
    }
    b = 42;
}
const a = new A();

愚蠢赋值的结果取决于哪个属性是在此之前创建的,哪个不是,以及创建的属性是如何初始化的。由于

this.b
在分配之前已经存在,因此它仍然不是
undefined
,与
this.b
不同。至于
this.a
,它变得未定义,因为您将未定义的属性分配给它的值,即分配时的
undefined

—请执行此代码片段。

如果你愿意的话,可以称其为魔法,但实际上这只是在开玩笑。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.