Javascript对象继承

标签 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']);

我期望输出是 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/

相关文章:

oop - 设计干净界面的指南

c# - 将 C# arraylist 传递给 Javascript

c# - 对象初始值设定项和构造函数

javascript - 如何使用javascript查找二维数组的中心元素的索引?

javascript - 在验证器中添加自定义规则以检查 <ul> 是否有元素

c# - 访问 UWP 页面之间传递的参数

Javascript 对象说明

javascript - 自动激活锚定选项卡

javascript - 在另一个对象中创建复杂/嵌套的 JavaScript 对象的正确方法

javascript - MyObj.prototype。对比这个