简体   繁体   中英

How to get current property function's name - JavaScript

I have an object that looks like below. Basically it contains properties that call a method. What I would like to be able to do is, instead of having DEVELOPER twice (Once for the property name and once for the parameter value), I'd like to get the current property of what was called in order to get this.

Also I don't want to pass in 'DEVELOPER' as a parameter in the initial call because I want intellisense to pick it up.

return {
   DEVELOPER: function ()
            {
                return getEmailRecipients("DEVELOPER")
            }
}
 //it get's called like this.
 emailGroups.DEVELOPER();

Essentially I'd like to do something like

return {
   DEVELOPER: function ()
            {
                return getEmailRecipients({this.currentPropName}) //Which would equal DEVELOPER.
            }
}

If there is a better way to do this, I am all ears.

Thanks in advance!

As far as I know, this is not possible, or at least it's not built-in.

You can use the function name as defined in arguments.callee like this...

arguments.callee.name

But the name property of functions is not well supported.

You might try something like this...

this.toSource().match(/\{(.*?):/)[1].trim ()

But that only works for one item in an object, and only the first item.

You might also try defining the object you return as a variable, and loop over that object giving every item a new property that contains the item name.

Like so...

// Object to return to emailGroups
var data = {
    DEVELOPER: function ()
    {
        return getEmailRecipients (arguments.callee.givenName)
    }
}

// Give each object item a new property containing the name
for (var name in data) {
    if (data.hasOwnProperty (name) === true) {
        data[name].givenName = name;
    }
}

// Return data variable as emailGroups
return data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM