[英]How can I get a property name inside the property itself in Javascript?
Is there a way I can get a property`s name inside the property itself? 有没有办法可以在属性本身中获得属性的名称?
I mean something like this: 我的意思是这样的:
let myObj = {
myProperty: {
name: <propertyName>.toString()
}
};
console.log(myObj.myProperty.name); // Prints `myProperty`
No, there isn't. 不,没有。 There's nothing available when the object initializer is evaluated that provides that information.
评估提供该信息的对象初始值设定项时,没有任何可用的方法。
Presumably if this were a one-off, you'd just repeat the name. 大概是一次性的话,您只需重复这个名字即可。 If it's not a one-off, you could give yourself a utility function to do it:
如果不是一次性的,则可以给自己一个实用程序函数来执行此操作:
// Define it once... const addProp = (obj, name, value = {}) => { obj[name] = value; value.name = name; return obj; }; // Then using it... let myObj = {}; addProp(myObj, "myProperty"); addProp(myObj, "myOtherProperty", {foo: "bar"}); console.log(myObj.myProperty.name); console.log(myObj.myOtherProperty.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.