Let's say I have an array 'x' and array x has 100 instances of an object. Lets say after I made this array of instances, I wanted to add an additional method to each instance within array x, how would I go about doing this?
Thanks!
Let's say I have an array 'x' and array x has 100 instances of an object. Lets say after I made this array of instances, I wanted to add an additional method to each instance within array x, how would I go about doing this?
Thanks!
If they are instances of some common class try this:
// create a class
class Item {
constructor() {
this.x = Math.random() * 10 | 0;
}
}
// create instances
const items = [...Array(100).keys()].map(() => new Item())
// add missing method
Item.prototype.print = function() {
console.log(this.x)
}
// test added method
items.forEach(item => item.print())
In the other case, you can just add a function to each instance
// generate objects
const items = [...Array(100).keys()].map(() => ({
x: Math.random() * 10 | 0
}))
// add a function to each object
items.forEach(item => item.print = function() {
console.log(this.x)
})
// test the added function
items.forEach(item => item.print())
Use a for loop to iterate over the array items and assign your method to each object:
x = [...];
for (var i = 0; i < x.length ; i++) {
x[i].method = func () {...};
}