imdadhusen
imdadhusen

Reputation: 2494

How to get function name passed as parameter for callback purpose using Javascript

I have following sample of code to get the function name which is passed in parameter for callback purpose.

var operation = {
    display : function(fun) {
        console.log('operation "'+ fun.toString() +'" performing' );
        //here i am getting
        /*operation "function () { 
                console.log('operation "subtraction" performed' ); }" performing
        */
        // **instead of entire function i would like to get only method name**
        fun.call();
    },
    addition : function() {
        console.log('operation "addition" performed' );
    },
    subtraction : function() {
        console.log('operation "subtraction" performed' );
    },
    multiplication : function() {
        console.log('operation "multiplication" performed' );
    }
}
operation.display(operation.subtraction);
//Output should be
// operation "subtraction" performing
// operation "subtraction" performed
operation.display(operation.multiplication);
//Output should be
// operation "multiplication" performing
// operation "multiplication" performed
operation.display(operation.addition);
//Output should be
// operation "addition" performing
// operation "addition" performed

Upvotes: 0

Views: 464

Answers (2)

Paul S.
Paul S.

Reputation: 66304

Your functions are anonymous; i.e. they are nameless function expressions. Before you can get their names, you have to give them names.

var o = {
    foo: function bar() {} // named function expression, name is "bar"
};
function getName(fn) {
    return fn.name;
}
getName(o.foo); // "bar"

The functions, however, do have related keys in your operation Object, but you can not find out which key of an Object something was for certain, code to find a match would be a guess because values don't have to be unique.

function guessKey(val, obj) {
    var key;
    for (key in obj)
        if (obj[key] === val)
            return key;
    return null;
}
guessKey(o.foo, o); // "foo"

Function.prototype.name shim for IE9+ (maybe also 8; not sure)

if (Function.prototype.name === undefined) { // may be "" so can't use !
    Object.defineProperty(Function.prototype, "name", {
        get: function () {
                var s = Function.prototype.toString.call(this);
                return s.slice(9, s.indexOf('('));
            }
    });
}

Upvotes: 2

rakeden
rakeden

Reputation: 192

the function object contains the "name" property returning the name of the method

UPDATE AS IE does not implement the name property for functions use a RegEx ;) This little function can help you out:

function getFnName(fn) {
  var f = typeof fn == 'function';
  var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
  return (!f && 'not a function') || (s && s[1] || 'anonymous');
}

Seen here: https://gist.github.com/dfkaye/6384439

Upvotes: 1

Related Questions