规范中是否有为类定义 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() {
}
}`;
附言
- 请注意,我在反引号
``
中写了字符串。我这样做是为了指定多行字符串。 - 规范还指出,
在表示字符串中使用和放置空格、行终止符和分号是依赖于实现的
。但现在所有的 JS 实现都保持不变。 - 您可以在 Chrome Canary 中测试示例,它现在支持 ES6 类。
关于JavaScript 的类 : toString() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865494/