Skip to content
Advertisement

Javascript instantiate user-defined class object from given object does not set all properties

i have a user-defined class PaymentCoordinator in javascript with a constructor looking as shown below:

constructor(
private amount: number,
private description: string,
private title: string,
private transactionType: string,
private creditors: Array<any>,
private categories: Array<string>,
private startdate: Date = undefined,
private enddate: Date = undefined,
obj: any = false)

The last property in the constructor obj is used to instantiate a PaymentCoordinator object from a given object obj – which is like clone the given object. In the constructor, if a obj is given (obj !== false) i do the cloning as follows:

obj && Object.assign(this, obj);

All properties of the given obj are set corretly – except for the one property categories which is a array of strings.

I also tried:

obj && Object.assign(this, obj);
this.categories = obj.categories

But this does also not set the categories property on the new created object.

If i plot the obj.categories i verified that the array contains strings.

Any ideas why this is not working?

Advertisement

Answer

Objects in JavaScript are passed by reference

const obj = { array: [1, 2, 3] }
const clone = Object.assign({}, obj)
console.log(clone.array)
obj.array.length = 0
console.log(clone.array)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement