Reputation: 5146
I am trying to substitute an anonymous function call in javascript, for a real function in a forEach.
What I have is something like:
whatever: function( importantParam ) {
array.forEach( function ( val ) {
if ( val === importantParam ) console.log( "OK" );
} );
}
What I want to achieve is something like:
whatever: function( importantParam ) {
array.forEach(this.whatever2,this);
},
whatever2: function( p1, importantParam) {
if ( p1 === importantParam ) console.log( "OK" );
}
So the problem is that I don't really know how to pass the importantParam when i call whatever2 inside forEach, since it takes a function as argument with 2 arguments for they index and the value, and nothing else.
Upvotes: 1
Views: 1820
Reputation: 66404
You'll need to wrap whatever2
somehow, e.g. using .bind
var array = [1, 2, 3],
obj;
obj = {
whatever: function (importantParam) {
array.forEach(this.whatever2.bind(this, importantParam));
},
whatever2: function (importantParam, p1) {
if (p1 === importantParam)
console.log("OK");
}
};
obj.whatever(2); // logs OK
In ES6 you can clean this up and use arrow functions
let obj = {
whatever(importantParam) {
array.forEach(x => this.whatever2(x, importantParam));
},
whatever2(p1, importantParam) {
if (p1 === importantParam)
console.log("OK");
}
};
Please note that this example use case you've provided looks like you should actually use .some
instead of .forEach
and return true
where you do the log
Upvotes: 1
Reputation: 45106
Wrap it with another function
whatever: function( importantParam ) {
array.forEach(function(item) {
this.whatever2(item, importantParam);
},this);
},
or switch the order of arguments and use bind
to partially apply callback
whatever: function( importantParam ) {
array.forEach(this.whatever2.bind(this, importantParam));
},
whatever2: function(importantParam, p1) {
if ( p1 === importantParam ) console.log( "OK" );
}
Upvotes: 1