Javascript对象继承

Anj*_*nji 5 javascript oop object

请帮助我理解这段代码.

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']);
Run Code Online (Sandbox Code Playgroud)

我期待输出,Another person designation: Designation, person designation: undefined但令我惊讶的是我发现它`Another person designation: Designation, person designation: Designation.

根据我的说法,anotherPerson扩展person对象和属性设置anotherPersonperson对象不应该是可见的.我错了吗?或者这两个对象都指向同一个位置?

[编辑]

现在还有更多的惊喜.

我在上面添加了以下代码.

person.place = 'XYZ';
console.log(person['place'] + ', ' + anotherPerson['place']); // Expected: XYZ, undefined. Result: XYZ, XYZ.
Run Code Online (Sandbox Code Playgroud)

基于上述结果和答案,我认为两个对象都指的是同一个位置.现在我添加了几行

person = undefined;
console.log(anotherPerson['place']) //Expected: error, Result: XYZ. ??!?!?
console.log(person['place']) // Expected: error, Result: error.
Run Code Online (Sandbox Code Playgroud)

有人可以对我有所了解吗?感谢您的帮助

Hal*_*yon 2

您没有进行扩展或任何类型的继承。

这更接近:

var Person = function () {
    this["first-name"] = 'FirstName',
    this["last-name"] = 'LastName',
    this["gender"] = 'Male'
};

var person = new Person();
var anotherPerson = new Person();
Run Code Online (Sandbox Code Playgroud)

现在您有两个独立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
Run Code Online (Sandbox Code Playgroud)