Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get the name of a calling function in Javascript?

Tags:

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. Thank you. I then looked into the problem of calling a recursive, or parent function within an object and found a solution here. This would allow me to retrieve the function name without using the arguments.callee/caller properties.

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

like image 785
Matt Avatar asked Feb 20 '23 04:02

Matt


1 Answers

A function's name is an immutable property of that function, set in the initial function expression.

var notTheName = function thisIsTheName() { ... }

someObj.stillNotTheName = function stillTheName() { ... }

If your function expression does not have a name, there is (unsurprisingly) no way to identify it by name. Assigning a function to a variable does not give it a name; if that were the case, you could not determine the name of an expression assigned to multiple variables.

You should set firstFunction's name property by expressing it as

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

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

like image 58
apsillers Avatar answered Mar 07 '23 18:03

apsillers