Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't everything assignable in JavaScript? [duplicate]

Tags:

javascript

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!?

like image 517
Kees C. Bakker Avatar asked Sep 17 '15 12:09

Kees C. Bakker


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.

How do you copy properties from one object to another JS?

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.

How do you make a deep copy in JavaScript?

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.


1 Answers

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.)

like image 52
Pointy Avatar answered Sep 21 '22 12:09

Pointy