简体   繁体   English

如何在Javascript的属性本身中获取属性名称?

[英]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.

相关问题 如果Javascript对象具有保存对函数的引用的属性,是否可以从函数本身中获取该属性名称? - If a Javascript object has a property which holds a reference to a function, can I get that property name from within the function itself? 如何从对象内部获取属性名称以创建新的属性名称? - How can I get the name of a property from inside an object to create a new property name? 我如何在 JSON 的属性中获取属性? - how i get a property inside of property of a JSON? 我可以获得以数字开头的 javascript object 属性名称吗? - Can I get a javascript object property name that starts with a number? 不知道属性名称时如何从javascript对象获取值 - How can I get a value from a javascript object when I don't know the property name 我可以解构一个变量,其中属性名称由变量本身定义吗? - Can I destructure a variable where property name defined by a variable itself? 如何替换对象内部的属性名称? 使用Javascript - How can I replace property names inside of an object? Javascript JavaScript我可以直接访问object里面的一个属性吗? - JavaScript can I directly access to a property inside a property in the object? “ jcanvas”我无法在图层本身中获取“数据属性” - “jcanvas” I can't get “data property” within the layer itself 如何获取特定 Javascript 属性的名称? - How to get the name of a specific Javascript property?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM