Reputation: 7110
If I have an array of objects like:
function Fruit() {
this.onTree = true;
}
Fruit.prototype.pick = function() {
this.onTree = false;
};
var arr = [new Fruit(), new Fruit()];
Is there any way to use Array.forEach to call the pick
method on each one without creating an extra anonymous function?
arr.forEach(function(f) { f.pick(); });
I thought maybe I could do something with Fruit.prototype.pick.call
but then the this
context of the call
function is lost so I have to bind
that and I end up with:
arr.forEach(Function.call.bind(Fruit.prototype.pick));
which works but it's pretty ugly. Basically I just want something like this from Java:
arr.forEach(Fruit::pick);
Upvotes: 1
Views: 232
Reputation: 400
If you cannot use ES6 (but, well, it's 2017...) you can store your this
reference
var self = this;
function invoker(item){
Item.pick.call(self);
}
array.forEach(invoker)
Or just use a for
loop
Upvotes: 0
Reputation: 1087
You missed ()
after Fruit definition, didn't you?
function Fruit() {
this.onTree = true;
}
Fruit.prototype.pick = function() {
this.onTree = false;
};
var arr = [new Fruit(), new Fruit()];
arr.forEach(function(val, index) {
val.pick();
console.log(val);
})
I tested that one nd it change those fruit.onTree into false.
Upvotes: 1
Reputation: 68665
You can use many approaches, but at least you need to pass a function to forEach
because that is it's syntax. But if you use ES6
, you can work with arrow functions
and it can be more beautiful.
arr.forEach(f => f.pick());
Upvotes: 5