i have a user-defined class PaymentCoordinator
in javascript with a constructor looking as shown below:
JavaScript
x
11
11
1
constructor(
2
private amount: number,
3
private description: string,
4
private title: string,
5
private transactionType: string,
6
private creditors: Array<any>,
7
private categories: Array<string>,
8
private startdate: Date = undefined,
9
private enddate: Date = undefined,
10
obj: any = false)
11
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:
JavaScript
1
2
1
obj && Object.assign(this, obj);
2
All properties of the given obj
are set corretly – except for the one property categories
which is a array of strings.
I also tried:
JavaScript
1
3
1
obj && Object.assign(this, obj);
2
this.categories = obj.categories
3
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
JavaScript
1
5
1
const obj = { array: [1, 2, 3] }
2
const clone = Object.assign({}, obj)
3
console.log(clone.array)
4
obj.array.length = 0
5
console.log(clone.array)