-1

I've tried this code for reach 'keyone' and it works.

const json = {
    'keyone' : function () {
         console.log(Object.keys(this)[0]) // it prints keyone when call json.keyone()
     } ,
    'keytwo' : function () {
         console.log(Object.keys(this)[1]) // it prints keytwo when call json.keytwo()
     }
}
json.keyone();
json.keytwo();

This code doesn't work in the browser, this returns window. I want it to return the key's name for the function, like in the below example:

...

'keyname' : function(){
    console.log('code for printing this function's keyname')
}

...

How can I do that?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
natrollus
  • 321
  • 1
  • 4
  • 11

1 Answers1

3

There's no reasonable way for the function you've called to know the name of the property referring to it. You'll need to change your structure if you want that. One way to do that is to bind the name of the function to it as its first argument:

const json = {
    'keyone' : function (name) {
         console.log(name);
     } ,
     'keytwo' : function (name) {
         console.log(name);
     }
};
for (const [key, func] of Object.entries(json)) {
    json[key] = func.bind(null, key);
}

json.keyone(); // "keyone"
json.keytwo(); // "keytwo"

The unreasonable way to do it without changing your structure, which won't work in strict mode and which I do not recommend, is to use arguments.callee.name in a modern browser. In a modern browser, your functions have names (they get their name from the property you're assigning them to). The deprecated arguments.callee property gives you a reference to the called function, and you can get its name from that:

const json = {
    'keyone' : function () {
         console.log(arguments.callee.name);
     } ,
     'keytwo' : function () {
         console.log(arguments.callee.name);
     }
};

json.keyone();
json.keytwo();

But again, I strongly recommend changing your structure instead. callee is deprecated, and doesn't work in strict mode, and older browsers (ones that don't support ES2015's implied function names) don't assign the function name.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875