I’m using shortcut.js to handle keyboard input and I’m wondering if there is a more efficient way to achieve my goal (currently most of the same code is copied and pasted).
For example, i have:
shortcut.add("0",function() {
points = -1;
sec = 0;
});
shortcut.add("1",function() {
points = 1;
sec = 0;
});
shortcut.add("2",function() {
points = 2;
sec = 0;
});
shortcut.add("3",function() {
points = 3;
sec = 0;
});
Ideally, I can generalize the function so that whatever key is entered is actually assigned to the points variable, except in the case where the user enters 0. In that case, the points variable is set to -1.
Any ideas on how to make this happen? Thank you!
A loop with a closure should do the trick:
Update following comment: So why do we need a closure here? And what does the final
(i);mean?Basically, we need a closure because the anonymous functions passed to
shortcut.add()will not be called right away, but some time in the future, after the loop has terminated. The functions captureiby reference, not by value, which means they will see the value ofithat is current at the time they run, not at the time they’re defined.So, if we call
shortcut.add()directly from the loop body, all the anonymous functions we pass will end up seeing the value ofithat is current after the loop has terminated, which will always be the same (10).Creating a new variable in each iteration looks like it could work, but doesn’t:
Since
forloop bodies do not have their own scope in Javascript,_iends up in function scope, the same asi, and will be captured the same way (its final value will be9instead of10because++idoes not apply to it).So, what we really need here is a new scope in each iteration. To achieve this, we can define a function inside the loop, and call it immediately, passing it the current value of
i:Finally, we can do that without introducing the
newScopename, by directly applying the call operator()to the function definition:I hope this appropriately answers your questions, feel free to leave further comments if it does not. For more information about closures, see Closures on MDN.