I’m playing with JS a bit and have following code snippet
var Dog = function(name) {
this.name = name
}
Dog.prototype= {
'bark': function() {
alert(this.name + ' is barking');
},
'run': function() {
alert(this.name + ' is running');
}
}
var dogs = [new Dog('first'), new Dog('second'), new Dog('third')];
function invokeOnDog(what) {
if(what === 'bark') {
for(var i=0; i<dogs.length; i++) {
dogs[i].bark();
}
}
if(what === 'run') {
for(var i=0; i<dogs.length; i++) {
dogs[i].run();
}
}
}
What I’d like to do is to simplify this invokeOnDog function cause it repeats the same template twice. I’m thinking about somehow returning method that should be invoked on object but have no idea how to do that.
Could you help me with that?
EDIT:
Thanks for quick responses. They are ok if “what” has the same name as method to invoke. But what if there is no match between those two?
invokeOnDog('aggresive') should invoke bark method and invokeOnDog('scared') should invoke run
You can access a object property (in this case the ‘bark’ and the ‘run’ method) from a string if instead of
You use
And if you have “property” in a variable you can do
Since you have a variable with the name of the method you want to call you can call the method with:
So it will be like this:
Update:
If the variable has no relation with the method you want to call you can use a mapping to set the relations:
This is the simplest code, but I recommend you to check if “position” value is a key on “methods” and not an inherited method:
Otherwise “invokeOnDog(‘toString’)” will access “methods[‘toString’]” who is a function.