简体   繁体   中英

Obtain property name within anonymous function in Javascript

Is it possible to get the name of the property that called the anonymous function in javascript?

Example

var obj = {
     WhoAmI: function() {
       //Obtain the name WhoAmI
     }
}

The function has no (direct) idea what the name of the property or variable is that references it.

Though depending on the means of invocation, it could be discovered.

var obj = {
     WhoAmI: function func() {
         for (var p in this)
             if (this[p] === func)
                 alert(p);
     }
}

obj.WhoAmI();

DEMO: http://jsfiddle.net/wUdNf/

This only works if the function is invoked with its this set as the object referencing it.

You could use arguments.callee instead of giving the function a name, though that's not permitted in strict mode .

var obj = {
    WhoAmI: function() {
        for (var prop in this){
            if (this[prop] === arguments.callee){
                console.log(prop);  // => 'WhoAmI'
            }
        }
    }
}

obj.WhoAmI();

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