I am trying to edit every function under the UI "class" to return their first argument but still run their native code.
Here is what I have tried:
for(var i in UI) {
var cur = UI[i];
UI[i] = function() {
cur.call(this, arguments);
return arguments[0];
}
}
This returns my arguments but no longer runs the original function correctly as the UI element is not called.
Thanks in advance.
1 Answer 1
Typical JavaScript closure inside loops – simple practical example problem. There is only a single cur variable in your scope and it will have the value assigned to it in the last iteration of the loop.
Use let and pass the arguments along properly (via rest args and apply):
for(let i in UI) {
let cur = UI[i];
UI[i] = function(...args) {
cur.apply(this, args);
return args[0];
}
}
If you are stuck with ES5:
for(var i in UI) {
(function(cur) {
UI[i] = function() {
cur.apply(this, Array.prototype.slice.call(arguments));
return arguments[0];
}
}(UI[i]));
}
curis not defined. Where did you define it and what do you expectthisto refer to?function(...args)instead of accessing it through arguments?.apply()in place of.call(). -- Passing arguments forward to another javascript function