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