Suppose I have an object like this:
var myObject = {};
myObject.myFunction = function() {
var name = ; // name should be myFunct
@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.