I know, this is normal object behavior.
The intent of the proposal is to make working with array/object more... convenient.
Code example:
let test1 = { arr: [] };
let test2 = {};
test2.arr = test1.arr; // reference bound to secondary location
test1.arr.push(1);
console.log(test2.arr[0]); // 1
test1.arr = []; // you as a developer actually want to clear the array, but you are rebinding a reference to `test1` which is no longer bound to `test2`
To prevent this behavior, you should always write your own array clearing method using this code:
for (let i = 0; i < test1.arr.length, i++) {
test1.arr.splice(i, 1);
i--;
}
It's not just this test
example that's the problem, but when people reference your deep configs somewhere in their own configs - all the getters/setters/refs lose their connection to the original location.
The object way is to keep references as long as possible, because they are "objects".
But javascript syntactic sugar usually suggests doing something like this:
let newArray = [].concat(oldArray);
or
let newArray = oldArray.filter(myFuncHere);
or
let newObject = { ...oldObject, newProp1: newValue1 };
All of these methods involve losing the reference to the original array, and this is probably the MOST COMMON javascript pitfall in general (second pitfall is to call setTimeout(this.method, 1000)
instead of setTimeout(this.method.bind(this), 1000)
)
It would be great to optimize sugar to work like this - short initializers (meaning let a = []
or let a = {}
) and all - binding new data to properties never recreates native objects (like PHP language does).
If you want to work with properties using object way, you will have to create new Object
or new Array
(without sugar), because you directly know what you are doing.