JavaScript
x
11
11
1
var that = this;
2
3
for(var i=0;i<x;++i){
4
// some code
5
events={
6
click: function(event){
7
that.doClick(event,this);
8
}
9
}
10
}
11
Now with above code I am getting JShint error:
“Dont make functions within loop”.
To resolve above error I am doing this now:
JavaScript
1
14
14
1
var that = this;
2
function clickHandler() {
3
return function() {
4
that.doClick(this);
5
};
6
}
7
8
for(var i=0;i<x;++i){
9
// some code
10
events={
11
click: clickHandler()
12
}
13
}
14
Is this fine? If yes then how can I pass event from click event to clickHandler
and then to doClick
function?
Advertisement
Answer
No, it’s not fine. The problem in creating functions inside a loop is that you create a new copy of the function at each iteration.
In your second code, you call clickHandler
at each iteration, which will return a different copy of the function each time. So it’s still the same problem.
Instead, a better way is creating the function only once before the loop, and reference it inside:
JavaScript
1
8
1
var that = this;
2
function clickHandler(event) {
3
that.doClick(event, this);
4
}
5
for(var i=0; i<x; ++i){
6
var events = {click: clickHandler};
7
}
8
However, since events
does not seem to depend on i
, you can move it outside too:
JavaScript
1
8
1
var that = this,
2
events = {click: function(event){
3
that.doClick(event, this);
4
}};
5
for(var i=0; i<x; ++i){
6
/* Use `events` here */
7
}
8