简体   繁体   中英

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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