请帮我理解这段代码。Javascript对象继承
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.
有人可以告诉我一些明白这一点吗? 感谢您的帮助提前
这里没有继承。只有两个引用同一个对象。 – Cameron 2012-04-27 19:59:51
那你怎么克隆这个对象并制作一个新对象呢?我和OP一样,可能会认为新建立了一个NEW对象。 – DanRedux 2012-04-27 20:01:36
请参阅:http://stackoverflow.com/questions/728360/copying-an-object-in-javascript – 2012-04-27 20:03:47