0

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)

4
  • You can't pass the key to the function? Commented Sep 5, 2015 at 3:28
  • @limelights: Do you mean like: hashes["a"]("a"); I can do it but I wanted to know if there is a way to do this without passing value. Commented Sep 5, 2015 at 3:31
  • 2
    There is no way that I'm aware of. The function doesn't actually belong to the hashes object 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 try arguments.callee.name, but that's deprecated and won't work in strict mode. Commented Sep 5, 2015 at 3:31
  • @nnnnnn: Thanks for your reply. I get you. But still, I will wait to see if there is any solution for this. I was using this as an alternative to switch case Commented Sep 5, 2015 at 3:35

1 Answer 1

1

Here's one way to do it:

var hashes = {
  'a': 'Fanta',
  'b': 'Pepsi',
  'c': 'Lemonade'
};

var logger = function( key, value ) {
  console.log( key );
  return value;
};

for ( var key in hashes ) {
  if ( hashes.hasOwnProperty( key ) ) {
    var value = hashes[ key ];
    hashes[ key ] = logger.bind( null, key, value );
  }
}

hashes.a(); // "a"
hashes.b(); // "b"
hashes.c(); // "c"

Demo on JSBin

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

2 Comments

Oh, wait.. I get your code now. Seems you are using 2 variables to achieve this.. But this will work...
Updated the code to use one hashes variable instead of two. Also removed dependency on lexical this.

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.