javascriptstatices6-classthis-pointer

How to make the this in the static function of the ES6 class point to the function itself


I want get the static function name in ES6 class, and I did not get the correct result when I did this.

class Point {
  static findPoint() {
    console.log(this.name) // <- I want to print "findPoint" but get "Point"
  }
}
Point.findPoint()

What can I do to get the name of the static method?


Solution

  • One option is to create an Error and examine its stack - the top item in the stack will be the name of the current function:

    class Point {
      static findPoint() {
        const e = new Error();
        const name = e.stack.match(/Function\.(\S+)/)[1];
        console.log(name);
      }
    }
    Point.findPoint();

    While error.stack is technically non-standard, it's compatible with every major browser, including IE.