2

我想知道是否可以从对象访问其父对象的属性,这是一个明确的示例,假设我们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());
4

2 回答 2

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);
    }
}
于 2013-07-09T09:16:05.993 回答
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());
于 2013-07-09T09:21:21.093 回答