简体   繁体   中英

How can Javascript automatically assign a value to an object?

I'm creating a JavaScript object - "obj". I want to be able to put into it ( obj.value1 = "text1" and obj.value2 = "text2" ) If I only create obj.value1 = "text1", obj.value2 should be automatically created with value1

I do not know how to do that. Possibly with get and set, but it doesn't work for me

You can wrap a getter to use value1 if value2 isn't set

 class MyClass { #_value2; constructor(value1, value2) { this.value1 = value1; this.value2 = value2; } set value2(value) { this._value2 = value; } get value2() { return this._value2 || this.value1; } } const myClass1 = new MyClass('text1', 'text2'); const myClass2 = new MyClass('text1'); console.log(myClass1.value2, myClass2.value2);

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