如何访问父对象属性?

时间:2013-07-09 09:14:30

标签: javascript

我想知道是否可以从一个对象访问其父级的属性,这是一个明确的示例,假设我们在People对象中有一个Group个对象的数组。

在这个Group对象中,每个People都有相同的地址,因此在Group而不是每个People对象中声明它会很好,但是如何在不解析集合的情况下访问它?

function Group() {
  this.address = 'EveryWhere';
  this.Collection = [];
} 

function People(data) {
  this.name = data.name;

  this.getAddress = function() {
    return this.address; //how to access it (declared in the Group object)?
  }
}

var Serie = new Group();
var John = new People();
Serie.Collection.push(John);
console.log(John.getAddress());

2 个答案:

答案 0 :(得分:2)

与许多语言相同:将父级传递给子级的构造函数,以便您可以保留对它的引用。

function People(data, parent) {
    this.parent = parent;
    this.getAddress = function() {
        return this.parent.address;
    }
}

为了使其更安全,您可以在父级上添加一个方法来添加子级:

function Group() {
    // ... other code ...
    function addPeople(data) {
        this.collection.push(new People(data, this);
    }
}

答案 1 :(得分:1)

您可以通过为Group

分配新的People.prototype对象来模仿继承
function Group() {
  this.address = 'EveryWhere';
  this.Collection = [];
} 


function People(data) {
  this.name = data.name;

  this.getAddress = function() {
    return this.address; //how to access it (declared in the Group object)?
  }
};

People.prototype = new Group();

var Serie = new Group();
var John = new People({name:"John"});
console.log(John.getAddress());