Javascript 使用构造函数创建对象数组

Javascript 使用构造函数创建对象数组,javascript,arrays,object,Javascript,Arrays,Object,我希望有一个包含Person对象的People数组,以便可以从数组索引访问对象中的字段 通常情况下,我会去和对象收集或列表等 你能帮我做这件事吗 var people = []; var person = { firstName:"John", age:50 }; function newPerson(){ var p = new person(); //<<< #1. Is this a good approach in

我希望有一个包含Person对象的People数组,以便可以从数组索引访问对象中的字段

通常情况下,我会去和对象收集或列表等

你能帮我做这件事吗

var people = [];

var person = {
    firstName:"John",
    age:50
  };



function newPerson(){       
    var p = new person();   //<<< #1. Is this a good approach in JS?
    p.firstName = "Fred";
    p.age = 21;

    people.push(p);
}


function totalAge(){

    var totalAge =0; 
    for (i = 0; i < people.length; i++){
        totalAge += people[i].age;   //<<<<< #2. This is the kind of access I want.
    }
}
var-people=[];
个人变量={
名字:“约翰”,
年龄:50
};
函数newPerson(){

var p=new person();//这样做

 var people = [];

function newPerson(){

    people.push({"firstName":"Fred", "age":21});
}


function totalAge(){

    var totalAge =0; 
    for (i = 0; i < people.length; i++){
          totalAge += people[i].age;   //<<<<< #2. This is the kind of access I want.
     }
}
var-people=[];
函数newPerson(){
推送({“名字”:“弗雷德”,“年龄”:21});
}
函数总数(){
var totalAge=0;
对于(i=0;itotalAge+=人[i].age;//这样做

 var people = [];

function newPerson(){

    people.push({"firstName":"Fred", "age":21});
}


function totalAge(){

    var totalAge =0; 
    for (i = 0; i < people.length; i++){
          totalAge += people[i].age;   //<<<<< #2. This is the kind of access I want.
     }
}
var-people=[];
函数newPerson(){
推送({“名字”:“弗雷德”,“年龄”:21});
}
函数总数(){
var totalAge=0;
对于(i=0;itotalAge+=people[i].age;//您可以使用
new
,但必须将其与构造函数一起使用(任何函数都可以用作构造函数)。
new
运算符不能应用于对象文字

function Person(firstName, age) {
    this.firstName = firstName;
    this.age = age;
}

var p = new Person('Fred', 21);

p.age; //21
如果要将一个对象用作另一个对象的原型,可以使用
object.create

var basePerson = { name: 'Default', age: 0 },
    p = Object.create(basePerson);

p.age; //0

您可以使用
new
,但必须将其与构造函数一起使用(任何函数都可以用作构造函数)。不能将
new
运算符应用于对象文本

function Person(firstName, age) {
    this.firstName = firstName;
    this.age = age;
}

var p = new Person('Fred', 21);

p.age; //21
如果要将一个对象用作另一个对象的原型,可以使用
object.create

var basePerson = { name: 'Default', age: 0 },
    p = Object.create(basePerson);

p.age; //0

您可以使用构造函数创建对象,如:-

 var people = [];
 //Person function behave as a class by this you can make new instance
 function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
 }

 var p1 = new Person("fred", 21);
 var p2 = new Person("Jhon", 24);
 people.push(p1, p2);


 function totalAge() {

   var totalAge = 0;
   for (i = 0; i < people.length; i++) {
      totalAge += people[i].age; //<<<<< #2. This is the kind of access I want.
   }
   return totalAge;
 }
var-people=[];
//Person函数作为一个类,通过它您可以创建新实例
职能人员(姓名、年龄){
this.firstName=fname;
这个。年龄=年龄;
}
变量p1=新人(“弗雷德”,21岁);
变量p2=新人(“Jhon”,24);
人。推(p1,p2);
函数总数(){
var totalAge=0;
对于(i=0;itotalAge+=people[i].age;//您可以使用构造函数创建如下对象:-

 var people = [];
 //Person function behave as a class by this you can make new instance
 function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
 }

 var p1 = new Person("fred", 21);
 var p2 = new Person("Jhon", 24);
 people.push(p1, p2);


 function totalAge() {

   var totalAge = 0;
   for (i = 0; i < people.length; i++) {
      totalAge += people[i].age; //<<<<< #2. This is the kind of access I want.
   }
   return totalAge;
 }
var-people=[];
//Person函数作为一个类,通过它您可以创建新实例
职能人员(姓名、年龄){
this.firstName=fname;
这个。年龄=年龄;
}
变量p1=新人(“弗雷德”,21岁);
变量p2=新人(“Jhon”,24);
人。推(p1,p2);
函数总数(){
var totalAge=0;
对于(i=0;itotalAge+=人[i]。年龄;//JS类

var Person = function(firstName, age) {
    this.firstName = '';
    this.age = '';
    this.createNewPerson=function(firstName, age) {
        this.firstName = firstName;
        this.age = age
    }
    this.createNewPerson(firstName, age)
}

var people = [];
var newPerson = new Person('harp',23);
people.push(newPerson)

JS中的类

var Person = function(firstName, age) {
    this.firstName = '';
    this.age = '';
    this.createNewPerson=function(firstName, age) {
        this.firstName = firstName;
        this.age = age
    }
    this.createNewPerson(firstName, age)
}

var people = [];
var newPerson = new Person('harp',23);
people.push(newPerson)
试试这个

var-people=[];
函数人(姓名、年龄){//函数构造函数
this.name=name;//不要忘记“this”
这个。年龄=年龄;
}
函数addPerson(姓名、年龄){
var p=newperson(name,age);//这里我们创建实例
人。推(p);
}
addPerson(“佩蒂亚”,80岁);
addPerson(“Vasia”,20);
函数总数(){
var total=0;//不要将局部变量命名为与函数相同的名称
var i;//对i变量使用var,否则它将是全局变量
对于(i=0;i
试试这个

var-people=[];
函数人(姓名、年龄){//函数构造函数
this.name=name;//不要忘记“this”
这个。年龄=年龄;
}
函数addPerson(姓名、年龄){
var p=newperson(name,age);//这里我们创建实例
人。推(p);
}
addPerson(“佩蒂亚”,80岁);
addPerson(“Vasia”,20);
函数总数(){
var total=0;//不要将局部变量命名为与函数相同的名称
var i;//对i变量使用var,否则它将是全局变量
对于(i=0;i
尝试以下操作:-

       function test(){
            var person = new Person('Jhon',10),
            person2 = new Person('Jhons',20),
            persons = [],total =0 ;
            persons.push(person);
            persons.push(person2);

            for(var i=0; i<persons.length; i++){
                total += persons[i].age;
            }
            console.log(persons,total);
        }
        function Person(name,age) {  
            this.name = name;
            this.age =age;
            return this;
        }
功能测试(){
var人员=新人员('Jhon',10),
person2=新人('Jhons',20),
人数=[],总数=0;
推(人);
人。推(人2);
对于(var i=0;i请尝试以下操作:-

       function test(){
            var person = new Person('Jhon',10),
            person2 = new Person('Jhons',20),
            persons = [],total =0 ;
            persons.push(person);
            persons.push(person2);

            for(var i=0; i<persons.length; i++){
                total += persons[i].age;
            }
            console.log(persons,total);
        }
        function Person(name,age) {  
            this.name = name;
            this.age =age;
            return this;
        }
功能测试(){
var人员=新人员('Jhon',10),
person2=新人('Jhons',20),
人数=[],总数=0;
推(人);
人。推(人2);
对于(var i=0;i更客观一点

function People() {
    this.people = [];
}

People.prototype.getTotalAge = function() {
   return this.people.reduce(function(totalAge, person) {
        return totalAge + person.age;
    }, 0); 
};

People.prototype.add = function() {
    var people = Array.prototype.slice.call(arguments);
    this.people = this.people.concat(people);
};

//Person function behave as a class by this you can make new instance
function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
}

var people = new People();
var p1 = new Person("fred", 21);
var p2 = new Person("John", 24);
people.add(p1, p2);

alert(people.getTotalAge());
资料来源:–多亏@Akhlesh

稍微客观一点

function People() {
    this.people = [];
}

People.prototype.getTotalAge = function() {
   return this.people.reduce(function(totalAge, person) {
        return totalAge + person.age;
    }, 0); 
};

People.prototype.add = function() {
    var people = Array.prototype.slice.call(arguments);
    this.people = this.people.concat(people);
};

//Person function behave as a class by this you can make new instance
function Person(fname, age) {
    this.firstName = fname;
    this.age = age;
}

var people = new People();
var p1 = new Person("fred", 21);
var p2 = new Person("John", 24);
people.add(p1, p2);

alert(people.getTotalAge());

来源:–多亏了@Akhlesh,这里有另一种使用原型的方法。 类(比如Java)对于JavaScript来说是一个相当陌生的概念,所以我建议不要尝试模仿它们

(function(){

    var people, Person, totalAge;

    // a Person prototype
    Person = Object.create({});

    // factory method creating Person objects
    Person.create = function Person_create (firstName, age) {

        var p = Object.create(Person);

        p._firstName = firstName;
        p._age = age;

        return p;

    };

    // getter for _age
    Person.getAge = function Person_getAge () {

        return this._age;

    };

    // generate some test values
    function populate (max) {

        var result, i;

        result = [];
        i = 0;

        while (i < max) {

            result.push(Person.create("Person"+i,i));
            i++;

        }


        return result;

    }

    // array containing test objects
    people = populate(100);

    // compute the sum of all Person.age
    totalAge = people.reduce(function(age,p){

        return age + p.getAge();

    }, 0); // <- 0 as initial value, basically you choose the neutral element for the operation in the given group (for multiplication initial value would be 1)

    console.log(totalAge);

}());
(函数(){
变量人、人、总年龄;
//人的原型
Person=Object.create({});
//创建Person对象的工厂方法
Person.create=函数Person\u create(名字、年龄){
var p=对象。创建(个人);
p、 _firstName=firstName;
p、 _年龄=年龄;
返回p;
};
//老年吸气剂
Person.getAge=函数Person\u getAge(){
把这个还给我;
};
//生成一些测试值
函数填充(最大值){
var结果,i;
结果=[];
i=0;
而(i},0);//这里是使用原型的另一种方法。
类(比如Java)对于JavaScript来说是一个相当陌生的概念,所以我建议不要尝试模仿它们

(function(){

    var people, Person, totalAge;

    // a Person prototype
    Person = Object.create({});

    // factory method creating Person objects
    Person.create = function Person_create (firstName, age) {

        var p = Object.create(Person);

        p._firstName = firstName;
        p._age = age;

        return p;

    };

    // getter for _age
    Person.getAge = function Person_getAge () {

        return this._age;

    };

    // generate some test values
    function populate (max) {

        var result, i;

        result = [];
        i = 0;

        while (i < max) {

            result.push(Person.create("Person"+i,i));
            i++;

        }


        return result;

    }

    // array containing test objects
    people = populate(100);

    // compute the sum of all Person.age
    totalAge = people.reduce(function(age,p){

        return age + p.getAge();

    }, 0); // <- 0 as initial value, basically you choose the neutral element for the operation in the given group (for multiplication initial value would be 1)

    console.log(totalAge);

}());
(函数(){
变量