Sitemap

Hidden recursion

1 min readSep 25, 2016

--

let flag = false;function foo() {
if (flag === false) {
flag = true;
// do something
flag = false;
}
}

What is this pattern? What is the flag doing here? The key part is in “do something”: it may call foo() again! So this is saying “if I am called inside of myself, don’t do something” or “I only wanna do something if I’m not called by myself”. A very good example is in autobind-decorator.

Get Steve Mao’s stories in your inbox

Join Medium for free to get updates from this writer.

// In IE11 calling Object.defineProperty has a side-effect of evaluating the
// getter for the property which is being replaced. This causes infinite
// recursion and an "Out of stack space" error.
let definingProperty = false;
return {
configurable: true,
get() {
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
return fn;
}
let boundFn = fn.bind(this);
definingProperty = true;
Object.defineProperty(this, key, {
value: boundFn,
configurable: true,
writable: true
});
definingProperty = false;
return boundFn;
}
};

It is not very obvious what definingProperty is doing here. In IE11 there is a bug that calling Object.defineProperty would call the getter of the property. So it’s a hidden recursion to IE11.

--

--