简体   繁体   English

在Javascript中获取匿名函数中的属性名称

[英]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? 是否有可能获得在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/ 演示: http //jsfiddle.net/wUdNf/

This only works if the function is invoked with its this set as the object referencing it. 这只有在功能与它的工作原理调用this设置为引用它的对象。

You could use arguments.callee instead of giving the function a name, though that's not permitted in strict mode . 您可以使用arguments.callee而不是为函数指定名称,但在严格模式下不允许这样做。

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

obj.WhoAmI();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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