Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple instances of objects in Javascript

I have a constructor object in my code which is:

function Employee(){
    this.name = names[Math.floor(Math.random() * names.length)];
    this.age=1;
    this.level=1;
    this.production=400;
    this.totalprod=0;
}

So when I create a new Employee I just say:

var employee1 = new Employee();

So then I can manipulate this instance of the object. Now, I want this objects to be created dynamically with the variable names: employee1, employee2, employee3 and so on.. Is there a way to achieve this or is it impossible?

And the other question that I have, say that I want to change the age of all instances at the same time, is there a way to do this? Thanks in advance and sorry if the question in silly, I'm learning!

EDIT: This is not the same as the other question as I'm using a constructor Object, not a literal Object, and, apart from that, I ask another question which is how to change a property of all instances at the same time, thanks!

like image 211
ALSD Minecraft Avatar asked Apr 13 '16 01:04

ALSD Minecraft


2 Answers

This isn't really possible without the use of something like eval, which is bad practice.

Instead if you knew how many employees you wanted to make in advance you could do something like this.

Example: https://jsfiddle.net/dbyw7p9x/

function makeEmployees(n) {
  var employees = new Array(n)
  for (var i = 0; i < n; ++i) {
    employees[i] = new Employee()
  }
  return employees
}

alternatively you could make also make it return an object which interestingly, while not exactly the same as the array, would be accessed in the same way as an array using numbers inside square brackets obj[0], obj[1], obj[2], obj[3] etc.

function makeEmployeesObj(n) {
  var employees = {}
  for (var i = 0; i < n; ++i) {
    employees[i] = new Employee()
  }
  return employees
}

To change a property for each approach you can do:

// Array
for (var i = 0; i < e1.length; ++i) {
    e1[i].age = 2
}

// Object
Object.keys(e2).forEach(function(key) {
    e2[key].age = 2
})
like image 128
m0meni Avatar answered Oct 12 '22 22:10

m0meni


Here is one way to do it, using an array, we push to new Employees to it, and return that array:

To add a specific value, in this case age, I recommend passing it in as a parameter to your Employee constructor, you can do this with all of the this parameters if you like:

Notice in the JsBin that all the ages are different, they are actually the value of n:

Working example: JSBin

    function Employee(age){
    this.name = 'something';
    this.age= age;
    this.level=1;
    this.production=400;
    this.totalprod=0;
}


function maker(n) {
  var arr = [];
  while (n > 0) {
    arr.push(new Employee(n));
    n--;
  }
  return arr;
}
like image 28
omarjmh Avatar answered Oct 12 '22 21:10

omarjmh