简体   繁体   中英

How is it possible to add an array argument to a constructor for an object, thus to give each object its own array?

Is it possible to have a object constructor where each objects has its own array?

I am have trouble figuring out the syntax if so.

Right now I am creating objects and a separate array to co-aside the object(waiters) array.

function Waiter (name, orders[]) {
    this.name = name;
    this.orders = orders;
}

// Constructor for waiter object
function Waiter (name) {
    this.name = name;
}

// Waiter objects
var waiterOne = new Waiter('Timo');
var waiterTwo = new Waiter('Lucian');
var waiterThree = new Waiter('Arpi');


// Array to store waiter object 
var waiters = [
    waiterOne,
    waiterTwo,
    waiterThree
];

// Count so that the same number of arrays are create as waiters
var countWaiterOrders = waiters.length;

// Creating a order array for each waiter object
for(var i = 0; i <= countWaiterOrders; i++){
    var order = [i];
}

Getting error:

Uncaught SyntaxError: Unexpected token [

Is the error message I get when trying to pass an array to the constructor.

The desired result would just be that each Waiter object has its own array for orders.

ex:

console.log(waiters[0]);

Waiter {name: "Timo", orders: []}

Silly question I was just a bit stuck for a while you assign the value to an empty array not the argument.

//Waiter constructor

function Waiter (name, order) {
    this.name = name;
    this.order = [];
}

Please correct me if I'm missing something, but it seems that you could just use something like this:

class Waiter {
      constructor(name) {
        this.name = name
        this.orders = []
      }
    }

What you are doing here is creating a class Waiter to which you pass a name as variable.

You can create a Waiter like so: var waiterOne = new Waiter('Tim') .

This would then allow you to use waiterOne.name or waiterOne.orders , as the array of orders is created in the constructor of the class.

If you wanted to store all your waiters in the array, the good method may be to create a collection class called Waiters - This could be useful if you wanted to do some operations on the whole collection of your Waiters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM