我有几个相同类型的对象,并且想从每个对象运行相同的函数:
function animal(name){
this.name = name
function foo(){
console.log(this.name);
}
}
var dog = new animal("dog");
var cat = new animal("cat");
var bird = new animal("bird");
通常,我会这样做:
dog.foo();
cat.foo();
bird.foo();
但是,如果我有一百个这样的对象,这并不是一种非常有效的方法。有没有办法只用几行代码就可以从每只动物运行 foo()?
最佳答案
嗯,要有效地做到这一点,您必须有效地组织您的对象。对多个对象进行排序的最有效方式通常是数组。因此,您创建了一个包含所有动物的数组,并对每只动物调用 foo。数组可以让你做到这一点,在代码中只调用一次函数,但它会在所有对象上发生。
在这里你必须考虑是否在任何时候都可能有没有 foo() 函数的动物。如果不是,请保持原样,如果是,则根据情况调用不同的函数或忽略该特定动物:
创建对象:
let animalArray = []
animalArray.push(new Animal("cat"))
animalArray.push(new Animal("dog"))
animalArray.push(new Animal("bird"))
animalArray.push(new Animal("hippo"))
在每个对象上调用 foo():
animalArray.forEach(animal => animal.foo())
ES5:
animalArray.forEach(function(animal){
animal.foo()
})
如果动物可能没有 foo():
animals.forEach(animal => {
if(animal.foo){
animal.foo()
}else{
//call other function or ignore and do nothing
animal.bar()
}
})
关于Javascript 从多个对象运行相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47851383/