If I have an array of Strings that represent numbers, and want to convert the type of every entry in the array to Number, I can use map
:
var stringNumbers = ["11", "23", "5813"];
stringNumbers.map(parseFloat);
// [11, 23, 5813]
This works because parseFloat
is globally accessible. However, if I want the result of an object's methods, I seem to need to use an anonymous function.
var Dog = function(name) {
this.name = name;
};
Dog.prototype.getName = function() {
return this.name;
};
var dogs = [new Dog("Beatrice"), new Dog("Baxter")];
dogs.map(function(dog) {
return dog.getName();
});
// ["Beatrice", "Baxter"]
Ideally, I would be able to do something like:
dogs.map(getName); // ["Beatrice", "Baxter"]
But this does not work because getName is not globally accessible.
Is there a way to bind each function executed by map
to the context of the object it is iterating over?