创建对象时调用函数

时间:2018-08-01 08:17:07

标签: javascript

使用构造函数创建新对象时是否可以调用函数?

let people = [];

function person(first, last){
   this.firstName = first;
   this.lastName = last;
}

let john = new person(john, doe);

现在,我希望将每个人推入一个数组。每次创建后我都必须写出array.push吗?

4 个答案:

答案 0 :(得分:5)

您可以为People使用另一个实例,并将Person添加到数组。

此方法不包括Person的副作用,因为people类涵盖了推送到People的情况。

function People() {
    this.people = [];
    this.createPerson = function (first, last) {
        this.people.push(new Person(first, last));
    };
    this.getPeople = function () {
        return this.people;
    };
}

function Person(first, last) {
    this.firstName = first;
    this.lastName = last;
}

var people = new People;

people.createPerson('john', 'doe');

console.log(people);
console.log(people.getPeople());
console.log(people.getPeople()[0] instanceof Person);

答案 1 :(得分:1)

怎么样:

let people = [];

function person(first, last){
   this.firstName = first;
   this.lastName = last;
   people.push(this);
}

let john = new person(john, doe);

答案 2 :(得分:1)

在创建person数组之前,将调用people构造函数。

let people = [];

function person(first, last) {
  this.firstName = first;
  this.lastName = last;
  this.pushToPerson = function() {
    people.push(this);
  }
  this.pushToPerson();
}

let john = new person("john", "doe");
console.log(people);

答案 3 :(得分:1)

    let people = [];

    function add (firstName, lastName) {
    let obj = {};
    obj.firstName = firstName;
    obj.lastName = lastName;
    people.push(obj);
    }

    add('John', 'Doe');
    add('Sarah', 'Smith');
    
    console.log(people);