请帮忙理解这段代码。
var person = {
'first-name': 'FirstName',
'last-name': 'LastName',
'gender': 'Male'
};
var anotherPerson = new Object(person);
anotherPerson.desig = 'Designation';
console.log('Another person designation: ' + anotherPerson['desig'] + ', person designation: ' + person['desig']);
我原以为输出结果应该是
Another person designation: Designation, person designation: undefined
,但令我惊讶的是结果居然是`Another person designation: Designation, person designation: Designation
。
根据我的理解,anotherPerson
是继承了 person
对象,并且赋值给 anotherPerson
的属性不应该对 person
对象可见。但是我错了吗?或者这两个对象都指向同一位置吗?
[编辑]
现在还有更多意外的事情发生了。
我在上述代码中添加了以下代码:
person.place = 'XYZ';
console.log(person['place'] + ', ' + anotherPerson['place']); // Expected: XYZ, undefined. Result: XYZ, XYZ.
根据上述结果和答案,我认为这两个对象都指向同一位置。现在我添加了几行代码。
person = undefined;
console.log(anotherPerson['place']) //Expected: error, Result: XYZ. ??!?!?
console.log(person['place']) // Expected: error, Result: error.
有人能为我解释一下这个吗?感谢您的帮助。