假设我有一个数组'x',数组x有100个对象实例。假设在我创建了这个实例数组之后,我想为数组x中的每个实例添加一个额外的方法,我该怎么做呢?
谢谢!
如果它们是一些常见类的实例,请尝试:
// 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())
在另一种情况下,您可以为每个实例添加一个函数
// 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())
使用for循环遍历数组项并将方法赋值给每个对象:
x = [...];
for (var i = 0; i < x.length ; i++) {
x[i].method = func () {...};
}