JavaScript 的类 : toString() method

标签 javascript ecmascript-6

规范中是否有为类定义 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

最佳答案

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

The string representation must have the syntax of a FunctionDeclaration FunctionExpression, GeneratorDeclaration, GeneratorExpession, ClassDeclaration, ClassExpression, ArrowFunction, MethodDefinition, or GeneratorMethod depending upon the actual characteristics of the object.

例如下一个类的“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() {
    }
}`;

附言

  1. 请注意,我在反引号 `` 中写了字符串。我这样做是为了指定多行字符串。
  2. 规范还指出,在表示字符串中使用和放置空格、行终止符和分号是依赖于实现的。但现在所有的 JS 实现都保持不变。
  3. 您可以在 Chrome Canary 中测试示例,它现在支持 ES6 类。

关于JavaScript 的类 : toString() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865494/

相关文章:

javascript - toLocaleDateString 返回意外的格式化时间

javascript - 使用groupBy时向JS中的对象添加值

javascript - 从异步函数返回的 promise 中获取值(value)

javascript - knockout 分页绑定(bind)

javascript - 无法将数据从 json 填充到 extjs 4 中的表单

尝试将新属性添加到 redux 状态时,javascript map.set 不起作用

javascript - 如何纠正这个缓存函数

javascript - 为什么类方法中的粗箭头没有绑定(bind)到父作用域的 this ?

javascript - 如何根据django admin中的另一个选择字段限制选择字段选项

javascript - 在 AngularJs 中链接两个 JSON 对象