How to get the name of the calling function in Javascript?

Consider the following example.

var obj = function(){}; function apply(target, obj) { if (target && obj && typeof obj == "object") { for (var prop in obj) { target[prop] = obj[prop]; } } return target; } apply(obj.prototype, { firstFunction: function (){ this.secondFunction(); }, secondFunction: function (){ // how do I know what function called me here? console.log("Callee Name: '" + arguments.callee.name + "'"); console.log("Caller Name: '" + arguments.callee.caller.name + "'"); } }); var instance = new obj(); instance.firstFunction(); 

UPDATE

Both answers are really awesome. Thanks. Then I looked at the problem of calling a recursive or parent function inside an object and found a solution here. This will allow me to get the name of the function without using the arguments.callee / caller properties.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/function

+4
source share
2 answers

The name of the function is an indisputable property of this function defined in the expression of the initial function.

 var notTheName = function thisIsTheName() { ... } someObj.stillNotTheName = function stillTheName() { ... } 

If a function expression has no name, there is (not surprisingly) a lack of a way to identify it by name. Assigning a function to a variable does not give it a name; If so, you cannot determine the name of the expression assigned to multiple variables.

You must set the firstFunction name property, expressing it as

 firstFunction: function firstFunction(){ this.secondFunction(); } 

In addition, arguments.callee deprecated. See Why is the arguments.callee.caller property deprecated in JavaScript? for a very good explanation of the history of arguments.callee .

+3
source

Name functions

as:

  var obj = function(){}; function apply(target, obj) { if (target && obj && typeof obj == "object") { for (var prop in obj) { target[prop] = obj[prop]; } } return target; } apply(obj.prototype, { firstFunction: function firstFunction(){ this.secondFunction(); }, secondFunction: function secondFunction(){ // how do I know what function called me here? console.log("Callee Name: '" + arguments.callee.name + "'"); console.log("Caller Name: '" + arguments.callee.caller.name + "'"); } }); var instance = new obj(); instance.firstFunction(); 

look at question

+4
source

Source: https://habr.com/ru/post/1434054/


All Articles