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.

asked Aug 17, 2020 at 5:08
5
  • 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? Commented Aug 17, 2020 at 5:16
  • isnt it better to use function(...args) instead of accessing it through arguments? Commented Aug 17, 2020 at 5: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. Commented Aug 17, 2020 at 5:24
  • 2
    Try using .apply() in place of .call(). -- Passing arguments forward to another javascript function Commented Aug 17, 2020 at 5: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. Commented Aug 17, 2020 at 6:16

1 Answer 1

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]));
}
answered Aug 17, 2020 at 7:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.