如何访问父对象属性?

时间:2022-09-06 19:25:56

I would like to know if it's possible from an object to access the properties of its parent, here is an explicite example, let's say we have an array of People objects in a Group object.

我想知道一个对象是否有可能访问它的父元素的属性,这里有一个解释的例子,假设我们有一个组对象中的对象数组。

In this Group object, every People have the same address, so it will be nice to declare it in the Group and not in each People objects, but how to access it without parsing the collection?

在这个组对象中,每个人都有相同的地址,所以在组中声明它,而不是在每个人对象中声明它,但是如何在不解析集合的情况下访问它呢?

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 个解决方案

#1


1  

You can mimic inheritance by assigning a new Group object to the People.prototype

您可以通过为People.prototype分配一个新的Group对象来模拟继承。

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());

#2


2  

Same as in many languages: pass the parent into the constructor of the child so you can hold a reference to it.

与许多语言一样:将父元素传递给子元素的构造函数,以便您可以对其进行引用。

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

To make it safer, you can add a method on the parent to add children:

为了使它更安全,您可以添加一个方法来添加子元素:

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

#1


1  

You can mimic inheritance by assigning a new Group object to the People.prototype

您可以通过为People.prototype分配一个新的Group对象来模拟继承。

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());

#2


2  

Same as in many languages: pass the parent into the constructor of the child so you can hold a reference to it.

与许多语言一样:将父元素传递给子元素的构造函数,以便您可以对其进行引用。

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

To make it safer, you can add a method on the parent to add children:

为了使它更安全,您可以添加一个方法来添加子元素:

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

相关文章