请帮助我理解这段代码。
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.
有人可以让我明白这一点吗? 提前感谢您的帮助
最佳答案
您没有进行扩展或任何类型的继承。
这更近了:
var Person = function () {
this["first-name"] = 'FirstName',
this["last-name"] = 'LastName',
this["gender"] = 'Male'
};
var person = new Person();
var anotherPerson = new Person();
现在您有两个独立 Person
实例。如果您还希望 anotherPerson
成为子类..
var Person = function () {
this["first-name"] = 'FirstName',
this["last-name"] = 'LastName',
this["gender"] = 'Male'
};
var AnotherPerson = function () {
this.desig = "Designation";
}
AnotherPerson.prototype = new Person(); // inherit from Person
AnotherPerson.prototype.constructor = AnotherPerson; // reset constructor
var person = new Person();
var anotherPerson = new AnotherPerson();
console.log(person.desig); // undefined
console.log(anotherPerson.desig); // Designation
关于Javascript对象继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10357033/