【问题标题】:JavaScript's classes: toString() methodJavaScript 的类:toString() 方法
【发布时间】:2015-01-09 17:00:00
【问题描述】:

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

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

class Foo {
  constructor() {
    console.log('hello');
  }
}

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

class Foo {
  constructor() {
    console.log('hello');
  }
}

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

function() {
  console.log('hello');
}

或者可能是构造函数,但它的名字是:

function Foo() {
  console.log('hello');
}

或者只是类名:

Foo

【问题讨论】:

  • 你试过运行代码了吗?
  • 你试过阅读规范吗?
  • 我已经阅读了规范 (people.mozilla.org/~jorendorff/…) 但没有任何内容。但也许我没有充分阅读它(toString 可能在其他地方定义?),或者类的行为就像它们的底层构造函数?如果代码不在规范中,则运行代码无关紧要,因为理论上我可以自己创建一个 ES6 运行时,它可以执行我在类上调用 toString() 时的任何感觉。
  • 重新阅读规范,我发现了 Felix Kling 所说的内容。谢谢!

标签: javascript ecmascript-6


【解决方案1】:

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

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

例如下一个类的'toString()':

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

    /**
     * Getting some name
     */
    getName() {
    }
}

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

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

    /**
     * Getting some name
     */
    getName() {
    }
}`;

PS

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2016-07-21
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多