Is there anything in the spec that defines a toString() method for classes?
For example, let's say I define this class:
class Foo {
constructor() {
console.log('hello');
}
}
If I called Foo.toString()
, I'm not sure if I'll get:
class Foo {
constructor() {
console.log('hello');
}
}
Or perhaps the constructor function, anonymous:
function() {
console.log('hello');
}
Or maybe the constructor function, but it's named:
function Foo() {
console.log('hello');
}
Or maybe just the class name:
Foo
Is there anything in the spec that defines a toString() method for classes?
For example, let's say I define this class:
class Foo {
constructor() {
console.log('hello');
}
}
If I called Foo.toString()
, I'm not sure if I'll get:
class Foo {
constructor() {
console.log('hello');
}
}
Or perhaps the constructor function, anonymous:
function() {
console.log('hello');
}
Or maybe the constructor function, but it's named:
function Foo() {
console.log('hello');
}
Or maybe just the class name:
Foo
- 4 Have you tried running the code? – chead23 Commented Jan 9, 2015 at 17:02
- 4 Have you tried reading the spec? – Barmar Commented Jan 9, 2015 at 17:02
- I've read the spec (people.mozilla/~jorendorff/…) but there's nothing there about it. But maybe I didn't read it fully enough (toString might be defined elsewhere?), or maybe classes act like their underlying constructor function? Running the code wouldn't matter if it's not in the spec, because I can theoretically create an ES6 runtime on my own that does whatever the heck I feel like when toString() is called on a class. – Daniel Weiner Commented Jan 9, 2015 at 17:07
- Re-read the spec and I found what Felix Kling is talking about. Thanks! – Daniel Weiner Commented Jan 9, 2015 at 17:22
1 Answer
Reset to default 7Actually in ES6 "class" is just a function. So to understand how toString
behave for so-called "classes" you must look at toString() specification for function. It says:
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.
So for example 'toString()' for the next class:
class Foo {
// some very important constructor
constructor() {
// body
}
/**
* Getting some name
*/
getName() {
}
}
toString()
method will return string:
Foo.toString() === `class Foo {
// some very important constructor
constructor() {
// body
}
/**
* Getting some name
*/
getName() {
}
}`;
PS
- Pay attention that I wrote the string in back quotes
``
. I did it to specify multiline string. - Also spec says that
use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent
. But now all JS realizations remains them unchanged. - You can test example in Chrome Canary, which now supports ES6 classes.