I was raised with the "everything in JavaScript object oriented and assignable" paradigm. So I lived my live happy, until...
var x = {};
x.field = true;
x.field.netType = "System.Boolean";
alert(x.field.netType);
It compiles, but the alert keeps giving met 'undefined'. Why!?
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.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Copy an Object With Object. assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
Primitives (strings, numbers, true
and false
) in JavaScript are not objects. However, when they are used with .
or []
as if they were objects, the language obliges by implicitly constructing object wrappers for them.
In your example, that's what happened. The assignment to the object property did actually work, so there was no error, but that wrapper object was then immediately thrown away.
On the other hand:
var x = {};
x.field = new Boolean(true);
x.field.netType = "System.Boolean";
alert(x.field.netType);
(I wouldn't advise actually doing that; using objects made from the primitive wrapper types tends to have weird effects as those values propagate into code that doesn't expect them.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With