0

Suppose I have an object like this:

var myObject = {};

myObject.myFunction = function() {
    var name = <some expression>; // name should be myFunction
}

Can I get the name of the object property to which the anonymous function is assigned inside the anonymous function?

8
  • 3
    What? I have no idea what this says.... Commented Jul 9, 2013 at 20:51
  • That function is anonymous. Commented Jul 9, 2013 at 20:52
  • It's not really anonymous, since you assigned it to a property on the object. Commented Jul 9, 2013 at 20:52
  • No, you can't do that. Commented Jul 9, 2013 at 20:52
  • 3
    @JimRubenstein: It's anonymous, the function itself has no name. myObject.myFunction.name == ''. But I thought OP wnated the function name, not the name of reference to that function. Commented Jul 9, 2013 at 20:53

2 Answers 2

4

There is no generic way to do this. If you call the function such that this refers to the object, you can iterate over the properties of the object and compare the values:

myObject.myFunction = function() { 
    var name;
    var func = arguments.callee;
    for (var prop in this) {
        if (this[prop] === func) {
            name = prop;
            break;
        }
    }
};

Note that the usage of arguments.callee is deprecated in favor of named function expressions. That is, you should do:

myObject.myFunction = function func() {  // <- named function expression
    var name;
    for (var prop in this) {
        if (this[prop] === func) {
            name = prop;
            break;
        }
    }
};

However, I wonder why you would need this. The property name should not have an impact on the inner workings of the function, and if it does, it seems to be badly designed IMO.

Sign up to request clarification or add additional context in comments.

Comments

0

@Felix Kling's solution is awesome but it depends on the function expression being named. As he said if you ever need to know the name of the property to which an anonymous function is being assigned then your code design is bad. Nevertheless, if you want to write bad code then please write it like this instead:

function anonymous(method) {
    return function () {
        var args = Array.prototype.slice.call(arguments), name = "";

        for (var key in this) {
            if (this[key] === method) {
                name = key;
                break;
            }
        }

        return method.apply(this, args.concat(name));
    };
}

Now you can create your anonymous functions like this:

var myObject = {};

myObject.myFunction = anonymous(function (name) {
    // function body
});

Remember that name must be the last argument of your function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.