I have an object like this which is a collection of key=>function pairs.
var hashes = {
"a": function () {
console.log($(this));
return 'Fanta';
},
'b': function () {
console.log($(this));
return 'Pepsi';
},
'c': function () {
console.log($(this));
return 'Lemonade';
}
};
hashes["a"]();
hashes["b"]();
I want to get the name of the key from within the function i.e. I was expecting console.log($(this)) to return "a" for 1st function, "b" for 2nd function and so on.. But since hashes is calling the function, it returns hashes object.
Is there any way to get key of the object from within the function (I need only corresponding key to the function being called)
hashesobject or to the individual key, rather that object property holds a reference to the function. You could have other references to the function that aren't part of the object, e.g.,var x = hashes.a; x();. (returns 'Fanta') If you give the functions names to match the keys you could tryarguments.callee.name, but that's deprecated and won't work in strict mode.