1

Is there a way to get method name and passed in parameter in javascript?

let

function say(param){
  alert(param);
}

so when say method is invoked,

say("helloworld")

I would get method: 'say' and parameters: {'helloworld'}

SpyClown
  • 199
  • 1
  • 1
  • 14
  • explain in more details with the html code – Bhavin Solanki Jul 15 '15 at 18:42
  • [Use Function.caller](http://stackoverflow.com/a/30687518/3345375) to get the calling function. Convert that function .toString(). Then [parse the string to get the function name](http://stackoverflow.com/a/28605792/3345375) and [use a regex to get the argument names](http://stackoverflow.com/a/14660057/3345375). As for the arguments' values, they're listed in a special object called "arguments" ([MDN link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)). – jkdev Sep 21 '15 at 02:34

2 Answers2

0
 function say() {
    var args = Array.prototype.slice.call(arguments);

    console.log("method:" + arguments.callee.name + " parameters: {" + JSON.stringify(args) + "}");
 }
Sagi
  • 8,972
  • 3
  • 33
  • 41
  • so does this work if i have `var x = {}; x.say = function(param){...}` i looked into the browser console and name was empty – SpyClown Jul 15 '15 at 19:17
  • There's no standard way to get the name of a function. Some browsers support it and some not. The answer is for your own example. in any other case things might be more complex. – Sagi Jul 15 '15 at 19:31
  • `x` is an object, `say` is a property of that object, and the value of `x.say` is an anonymous function... and [as this answer points out](http://stackoverflow.com/a/9422864/3345375), anonymous functions don't have names. – jkdev Jul 16 '15 at 11:30
0
function say(param){
  alert("method: " + arguments.callee.name + " and parameters : "+param);
}
Bhavin Panchani
  • 1,332
  • 11
  • 17