3

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.

Ultranite
  • 33
  • 4
  • Your code works as it is in the sense that it returns the first passed argument. But, clearly, `cur` is not defined. Where did you define it and what do you expect `this `to refer to? – Carsten Massmann Aug 17 '20 at 05:16
  • isnt it better to use `function(...args)` instead of accessing it through arguments? – bill.gates Aug 17 '20 at 05:19
  • Basically I think we need more context. I. e.: please provide a "minimum" version of your UI class and some code showing us how you instanciate the class into an object. – Carsten Massmann Aug 17 '20 at 05:24
  • 2
    Try using `.apply()` in place of `.call()`. -- [Passing arguments forward to another javascript function](https://stackoverflow.com/questions/3914557/passing-arguments-forward-to-another-javascript-function) – Jonathan Lonowski Aug 17 '20 at 05:24
  • UI isn't created by me, it's in the API that I'm using which is why I need to edit it but still run it. I tried apply, didn't work. – Ultranite Aug 17 '20 at 06:16

1 Answers1

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]));
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143