从javascript对象的属性获取密钥名称

时间:2017-12-08 19:44:24

标签: javascript object key

如何在功能中获取密钥名称“email”?是否有特殊的上下文变量来执行此操作?

感谢您的帮助。

var user = {
  "email": function() {
    // How can I get the name of the key (email) inside the function ?
  }
}

2 个答案:

答案 0 :(得分:1)

relatively new feature of JS将根据最初分配给它的变量或属性为匿名函数表达式指定名称。

您可以通过arguments.callee.name

访问功能名称

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.baz();

当然,如果您将该功能复制到其他地方,它将不会获得新名称。该名称在创建时被赋予。

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.foo = bar.baz;

bar.foo();

答案 1 :(得分:0)

我会通过提问来回答这个问题。请考虑以下情况:

let myFunc = function(){ /* somehow returns the name */ };

let a = {
    funcA: myFunc
};

let b = {
    funcB: myFunc
};

现在,请考虑一下:

a.funcA();
b.funcB();

他们应该回归什么? myFuncfuncAfuncB?答案是"它没有意义"。

这就是为什么你要做的事情是不可能的。该功能可以拥有"拥有"由不同的对象。