is this the correct way to return a copy of an object?
class ObjectWrapper { private _ obj; /*** * Copy object of argument to this._ obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of * this._ obj (Return copy this._ obj) * @return Object */ get obj () { return this._obj; }
I really was wondering what it means "returning a copy"
No, you are returning the original object. You have several options to copy an object in JS.
Traditional way through Object.assign()
:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
The Object.assign() method only copies enumerable and own properties from a source object to a target object.
ESNext approach with spread
operator:
const source = { a: 1, b: 2 };
const target = {...source};
The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.
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.