Yes, you are approaching it correctly, but for maximum compatibility with implementations you need to put parentheses around the function:
newInput.onchange = (function(x){
Whenever you execute an expression of a function and call it immediately, you need these partners, because otherwise there is a difference in the parsing.
Update
While your approach is beautiful, itβs worth noting that itβs a little wasteful. ;-) It creates two functions at each iteration of your loop, external anonymous and internal anonymous. Both of these functions adhere (prohibition of implementation optimization, which, as you know, some engines will not have). Instead, you can only have one per loop plus one factory function:
// In the loop newInput.onchange = makeHandler(x); // Outside the loop function makeHandler(x){ return function(){ PassFileName(x); }; }
Some may find it easier to read (of course I do), provided that makeHandler is still close enough to a loop that you won't lose.
Using the factory function also gives you the opportunity not to close anything else in scope, although then you need to add the factory function further (for example, in a well-defined area).
You can also consider general curry , for example, one of which is represented by a prototype . A general curry that does not pass call time arguments is as follows:
function curry(f) { var args = arguments; return function() { f.apply(undefined, args); }; }
But it is usually more useful (but more expensive) to have one that also passes runtime arguments. Here itβs cheaply dirty (not optimized, with optimization of the call waiting time it can be noticeably reduced):
function curry(f) { var args = Array.prototype.slice.call(arguments, 1); return function() { f.apply(undefined, args.concat(Array.prototype.slice.call(arguments))); }; }
The advantage in both cases is that you do not close anything new, which you can avoid.
Off topic . Also, technically, you rely on horror in which a semicolon is inserted (there should be a semicolon at the end of your return ), which I always defend without relying. However, this example is pretty safe .; -)