How to get the function name from within that function?

前端 未结 20 910
抹茶落季
抹茶落季 2020-11-22 16:06

How can I access a function name from inside that function?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  p         


        
20条回答
  •  悲哀的现实
    2020-11-22 16:43

    You can use name property to get the function name, unless you're using an anonymous function

    For example:

    var Person = function Person () {
      this.someMethod = function () {};
    };
    
    Person.prototype.getSomeMethodName = function () {
      return this.someMethod.name;
    };
    
    var p = new Person();
    // will return "", because someMethod is assigned with anonymous function
    console.log(p.getSomeMethodName());
    

    now let's try with named function

    var Person = function Person () {
      this.someMethod = function someMethod() {};
    };
    

    now you can use

    // will return "someMethod"
    p.getSomeMethodName()
    

提交回复
热议问题