Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript's classes: toString() method

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

like image 784
Daniel Weiner Avatar asked Oct 18 '25 10:10

Daniel Weiner


1 Answers

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

  1. Pay attention that I wrote the string in back quotes ``. I did it to specify multiline string.
  2. 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.
  3. You can test example in Chrome Canary, which now supports ES6 classes.
like image 190
alexpods Avatar answered Oct 20 '25 00:10

alexpods



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!