The situation is somewhat like-
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
The problem is that the value of someVar
is not visible inside the listener function of the addEventListener
, where it is probably being treated as a new variable.
Also try these (IE8 + Chrome. I dont know for FF):
Hope there is no typos :-)
Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the
this
object within the target function.Or to capture some of the lexical scope, for example in a loop:
Finally, if the
this
parameter is not needed within the target function:The following approach worked well for me. Modified from here.
There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.
Example:
One way is doing this with an outer function:
This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)
You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.