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

49 views Asked by At

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?

2

There are 2 answers

0
CertainPerformance On BEST ANSWER

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.

0
Rajkumar A On

this.name refers class name. Use this.findPoint.name to get static function name. Syntax must be object.someMethod.name. You have to say which method name you want. Hope this will help you.

class Point {
  static findPoint() {
    console.log(this.findPoint.name)
  }
}
Point.findPoint()