Yeo Eng Guan
Yeo Eng Guan

Reputation: 31

Why would this code lead to infinite loop/recursive

I have the following javascript code:

var original_selectCallback = window.selectCallback;
var selectCallback = function(variant, selector) {
  original_selectCallback(variant, selector);
  console.log(variant + " " + selector);
};

Somehow, the 2nd line:

var selectCallback = function(variant, selector) 

leads to a recursive call to selectCallback. My understanding is that I am redefining the selectCallback function. So why would this be a recursive call? Any suggestions/advice is appreciated.

Upvotes: 3

Views: 91

Answers (3)

plalx
plalx

Reputation: 43718

There is no recursion here and that is quite easy to demonstrate:

let someFn = function () { console.log('original'); };
let originalSomeFn = someFn;

someFn = function () {
  originalSomeFn();
  console.log('decorated');
};

someFn();

However, the original function may be involved in a recursive algorithm somewhere and your wrapper function might not entirely fulfill the proper behavioral contract of the original function.

To make sure here's how you should be wrapping the original function. I also opted for a closure to avoid a global originalSomeFn variable.

let someFn = function () {
    console.log('original');
    return 1;
};

someFn = (function (originalSomeFn) {
  return function () {
    let result = originalSomeFn.apply(this, arguments);

    console.log('decorated');

    return result;
  };
})(someFn);

console.log(someFn());

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129792

There is nothing inherently wrong with the code you've posted:

var selectCallback = function() { console.log('original'); };
var original_selectCallback = selectCallback;
var selectCallback = function() {
 original_selectCallback();
 console.log('wrapper');
};
selectCallback();

The error is likely in the initial definition of window.selectCallback, which is not shown here.

Upvotes: 1

Justinas
Justinas

Reputation: 43441

Let's check your code:

var original_selectCallback = window.selectCallback;

creates new variable that refers to function selectCallback.


var selectCallback = function(variant, selector) {

creates window.selectCallback function (because it's in window scope).


Now inner part of function

original_selectCallback(variant, selector);

will call window.original_selectCallback that is same as window.selectCallback that is same function where you are now.

So you make recursion with selectCallback that never ends.

Upvotes: -1

Related Questions