Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object.assign does not copy functions [duplicate]

I have a common typescript class with some functions.

When I do this.selected = Object.assign({} as AssignedTestType, newTestType);

the selected instance does not own that functions which are in the type AssignedTestType.

How can I make a 'deep' copy with object.assign? or any alternative method?

like image 441
Pascal Avatar asked Dec 21 '16 21:12

Pascal


People also ask

Does object assign make a copy?

Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.

Does object create Creates a deep copy?

assign() , and Object. create() ) do not create deep copies (instead, they create shallow copies). As can be seen from the code above, because a deep copy shares no references with its source object, any changes made to the deep copy do not affect the source object.

Does object assign mutate?

The first argument in Object. assign is called the “target” and will MUTATE.


2 Answers

object.assign does not copy functions

That's untrue

let x = {a: y => y * 2}
let z = Object.assign({}, x)
console.log(z.a(5)); // 10

the selected instance does not own that functions which are in the type AssignedTestType.

Now this part is true. Object.assign will only do a shallow copy and will only enumerate own props

like image 134
Mulan Avatar answered Oct 07 '22 12:10

Mulan


If the properties you're looking to copy are in the prototype of newTestType, they will not be copied, since Object.assign only copies an object instance's own properties.

The alternatives are to either instantiate whatever constructor you used to create newTestType, and assign the resulting instance to this.selected, or to create an empty object and set its prototype to newTestType. In either case, Object.assign is the wrong tool to use here.

like image 42
Asad Saeeduddin Avatar answered Oct 07 '22 12:10

Asad Saeeduddin