对象函数的javascript名称 [英] javascript name of object function

查看:55
本文介绍了对象函数的javascript名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的对象:

Suppose I have an object like this:

var myObject = {};

myObject.myFunction = function() {
    var name = <some expression>; // name should be myFunction
}

我是否可以获取对象属性的名称哪个匿名函数在匿名函数内分配?

Can I get the name of the object property to which the anonymous function is assigned inside the anonymous function?

推荐答案

没有通用的方法可以做到这一点。如果你调用函数这个引用该对象,你可以迭代对象的属性并比较这些值:

There is no generic way to do this. If you call the function such that this refers to the object, you can iterate over the properties of the object and compare the values:

myObject.myFunction = function() { 
    var name;
    var func = arguments.callee;
    for (var prop in this) {
        if (this[prop] === func) {
            name = prop;
            break;
        }
    }
};

请注意 arguments.callee 不赞成使用命名函数表达式。也就是说,你应该这样做:

Note that the usage of arguments.callee is deprecated in favor of named function expressions. That is, you should do:

myObject.myFunction = function func() {  // <- named function expression
    var name;
    for (var prop in this) {
        if (this[prop] === func) {
            name = prop;
            break;
        }
    }
};

但是,我想知道你为什么需要这个。属性名称不应该对函数的内部工作产生影响,如果确实如此,它似乎设计得很糟糕IMO。

However, I wonder why you would need this. The property name should not have an impact on the inner workings of the function, and if it does, it seems to be badly designed IMO.

这篇关于对象函数的javascript名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆