简体   繁体   中英

get this function's name within prototype definition

Is it possible to reference this function's name? For example:

'use strict'
function myClass(){}

myClass.prototype.myName = function myName(data,callback){
    console.log("This function has been called: " + "{???}"); // "myName"
}
myClass.prototype.myAge = function(data,callback){
    console.log("This function has been called: " + "{???}"); // "myAge"
}
var a = new myClass();
a.myName(); // 'myName'
a.myAge();  // 'myAge';

How can I reference " myName " in strict mode like that?

If this is just for debugging, you can use the following, which uses the stack trace to find a function's name, taking advantage of the browser magic that it does to find the "names" of functions. Tested in FF, Chrome and IE 10.

 function MyClass() {}; MyClass.prototype.myName = function() { console.log(getCallerName(), 'I am here'); }; MyClass.prototype.myOtherName = function() { console.log(getCallerName(), 'I am here again'); }; function doMe() { console.log(getCallerName(), 'I am here in a named function'); }; function getCallerName() { try { throw new Error(); } catch (e) { if (e.stack) { var lines = e.stack.split('\\n'); // FF (Maybe, Opera and Safari) var ffMatch = /\\b([a-zA-Z1-9\\$_\\.]*)@/.exec(lines[1]); if (ffMatch) { return ffMatch[1]; } // IE 10+ and chrome var chromeMatch = /at (.*) /.exec(lines[2]); if (chromeMatch) { return chromeMatch[1]; } } return 'unknown function'; } } var a = new MyClass(); a.myName(); a.myOtherName(); doMe(); 

Play with it at http://jsfiddle.net/ob0w4z3k/5/

You can use myName.name :

(function myName(){
    console.log("This functions name is " + myName.name);
})(); // "This functions name is myName"

However, note that this was introduced in ECMAScript 6, so most browsers don't support it yet.

Only Firefox has supported it for a long time, because it was a non-standard feature, before ES6 spec was made.

Also see the MDN article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM