这段代码中的“this”代表什么?

7

我正在阅读《你不知道的JavaScript:ES6与更高版本》,在Symbol.species章节中遇到了这段代码。

class Cool {
    // defer `@@species` to derived constructor
    static get [Symbol.species]() { return this; }

    again() {
        return new this.constructor[Symbol.species]();
    }
}

class Fun extends Cool {}

class Awesome extends Cool {
    // force `@@species` to be parent constructor
    static get [Symbol.species]() { return Cool; }
}

var a = new Fun(),
    b = new Awesome(),
    c = a.again(),
    d = b.again();

c instanceof Fun;           // true
d instanceof Awesome;       // false
d instanceof Cool;          // true

似乎函数Symbol.species { return Something }应该总是返回一个构造函数。但是在第一次出现这个函数时:static get [Symbol.species]() { return this; },我很困惑,因为我总是认为这应该是一个对象而不是一个构造函数。您能否帮助我澄清事实?
至于return new this.constructor[Symbol.species]();,这里的this指什么?
1个回答

6

this 在方法中指向的内容取决于它执行时所处的上下文。

在类方法、静态方法中,this 指向该类。

因此,例如:

static get [Symbol.species]() { return this; }

由于这是一个类方法,它将在类上执行,this将引用该类。

//since this is a getter we don't use trailing `()`
Cool[Symbol.species] === Cool;
//It does not exist on instances
var myCool = new Cool();
console.log( myCool[Symbol.species] );
//will give undefined

现在来看实例方法,比如“again”方法,它们只存在于实例中,因此从实例中调用而不是从类中调用:
console.log( Cool.again );
//will give undefined
var myCool = new Cool();
var newInstance = myCool.again();

在实例方法中,this 指的是实例,而不是类。

因此,给定:

 return new this.constructor[Symbol.species]();
  • this 是实例(例如,new Cool
  • this.constructor 是创建实例的构造函数(例如,Cool
  • this.constructor[Symbol.species] 是类获取器方法 Symbol.species
  • new this.constructor[Symbol.species]() 是 Symbol.species 返回的类的新实例

因此,整行代码返回一个新的类实例,该实例由静态获取器 Symbol.species 方法返回。

这使得一个类有了可以创建新类实例的方法,而不需要知道该类的名称。

因此,正如示例所示,即使 Fun 没有定义自己的 again 方法,again 也知道如何创建一个新的 Fun 实例。而且,正如 Awesome 所展示的那样,您只需覆盖 Symbol.species 以更改 again 将创建哪个实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接