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
Actually 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
``
. I did it to specify multiline string.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With