javascript - 这个片段中的这个是什么?

标签 javascript symbols

我正在阅读 You Don't Know JS: ES6 & Beyond 我在 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 new this.constructor[Symbol.species]();,这里的this指的是什么?

最佳答案

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 知道如何创建 的新实例>乐趣。正如 Awesome 所示,您只需覆盖 Symbol.species 即可更改 again 将创建的实例。

关于javascript - 这个片段中的这个是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37370780/

相关文章:

javascript - 这是什么错误 ERROR Cannot prepare tests due to an error.类型错误 : Cannot read property 'Date' of undefined?

lisp - Web 应用程序中符号的 Common Lisp 相等性

java - 当变量已经声明时,为什么我的 for 循环需要一个标识符?

c++ - Windbg 从改变的位置加载符号

ruby - 解决 yaml for Ruby 中的意外行为——驻留的 unicode 字符串

javascript - 我不明白这段代码片段中 "(oldest.years || 0)"的用法

javascript - webpack 样式加载器是用来加载所有 css 的吗?或者只是应用程序特定的 css?

javascript - Asp.net MVC,如何避免javascript中参数中的斜杠(/)

javascript - Ember 将 PATCH 调用转换为 PUT

c++ - 如何检查 makefile 中已定义符号(Eclipse-> 路径和符号)的值?