JavaScript 的类:toString() 方法

Dan*_*ner 3 javascript ecmascript-6

规范中是否有任何内容为类定义了 toString() 方法?

例如,假设我定义了这个类:

class Foo {
  constructor() {
    console.log('hello');
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我打电话Foo.toString(),我不确定我是否会得到:

class Foo {
  constructor() {
    console.log('hello');
  }
}
Run Code Online (Sandbox Code Playgroud)

或者也许是匿名的构造函数:

function() {
  console.log('hello');
}
Run Code Online (Sandbox Code Playgroud)

或者也许是构造函数,但它的名字是:

function Foo() {
  console.log('hello');
}
Run Code Online (Sandbox Code Playgroud)

或者也许只是类名:

Foo

ale*_*ods 6

实际上在 ES6 中,“类”只是一个函数。因此,要了解toString所谓的“类”的行为方式,您必须查看函数的 toString() 规范。它说:

字符串表示必须具有 FunctionDeclaration FunctionExpression、GeneratorDeclaration、GeneratorExpession、ClassDeclaration、ClassExpression、ArrowFunction、MethodDefinition 或 GeneratorMethod 的语法,具体取决于对象的实际特征。

因此,例如下一个类的“toString()”:

class Foo {
    // some very important constructor
    constructor() {
       // body
    }

    /**
     * Getting some name
     */
    getName() {
    }
}
Run Code Online (Sandbox Code Playgroud)

toString() 方法将返回字符串:

Foo.toString() === `class Foo {
    // some very important constructor
    constructor() {
       // body
    }

    /**
     * Getting some name
     */
    getName() {
    }
}`;
Run Code Online (Sandbox Code Playgroud)

聚苯乙烯

  1. 请注意,我在反引号中写了字符串``。我这样做是为了指定多行字符串。
  2. 规范也说use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent。但是现在所有的 JS 实现都保持不变。
  3. 您可以在 Chrome Canary 中测试示例,它现在支持 ES6 类。