【问题标题】:What does this in this snippet?这个片段中的这个是什么?
【发布时间】:2016-09-19 03:23:06
【问题描述】:

我正在阅读 You Don't Know JS: ES6 & Beyond,我在 Symbol.species 部分遇到了这个 sn-p。

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]();,这里指的是什么?

【问题讨论】:

    标签: javascript symbols


    【解决方案1】:

    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] 是类 getter 方法 Symbol.species
    • new this.constructor[Symbol.species]() 是 Symbol.species 返回的类的新实例

    因此,整行都返回了静态 getter Symbol.species 方法返回的类的新实例。

    这允许一个类拥有在不知道其名称的情况下创建一个类的新实例的方法。

    所以如示例所示,即使Fun 从未定义它自己的again 方法again 知道如何创建Fun 的新实例。正如Awesome 所示,您只需覆盖 Symbol.species 即可更改again 将创建的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      相关资源
      最近更新 更多