I have stumbled upon something that bugs me. I had to copy one object so I have written a helper function for that task.
function deepCopy2(target, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] !== 'object') {
target.prop = obj[prop];
} else {
var embedded = {};
deepCopy2(embedded, obj[prop]);
target.prop = embedded;
}
}
}
return target;
}
For some reason this doesn't work. So I have just changed .(dot) assignment into [ ] as is shown below, and it works.
function deepCopy1(target, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] !== 'object') {
target[prop] = obj[prop]; // changed here
} else {
var embedded = {};
deepCopy1(embedded, obj[prop]);
target[prop] = embedded; // changed here
}
}
}
return target;
}
If I do the following.
var obj = {
name: 'john',
getName: function() { return true; },
inner: { age: 23 }
};
var newObj1 = deepCopy1({}, obj);
var newObj2 = deepCopy2({}, obj);
console.log(obj);
console.log(newObj1);
console.log(newObj2);
I get
{name: "john", getName: ƒ, inner: {…}}
{name: "john", getName: ƒ, inner: {…}}
{prop: {…}}
Meaning that the first function failed and instead of copying properties one by one, It just created property called prop
.
I have found this Valid property names, property assignment and access in JavaScript as well as this JavaScript property access: dot notation vs. brackets? and searched also on MDN but nothing leads to the answer.
I have also looked whether prop
name can be freely used and didn't find any restrictions.
Can anyone explain to me why the first approach doesn't work while the second does?