1

Take a look at this piece of code

var obj = {
    foo: 5
};

var recursive = (function(){
    if(this.foo === 0){
        return;
    }

    this.foo--;
    recursive();
}).bind(obj);

Does the recursive function create a circular reference? If or if not, why?

EDIT: Circular reference between the function recursive and itself. I also found something similar here

1 Answers1

2

Does the recursive function definition create a circular reference, like this one here?

Yes, it still does. bind doesn't change that, although it introduces an additional link in the reference circle.

  • The variable recursive holds the bound function
  • The bound function (created from the .bind() call) contains a slot with the original function
  • The original function (created from the function expression) closes over the variable scope that contains recursive
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • How can I redesign it so it avoids a circular reference? – Juan Dela Cruz Oct 13 '17 at 13:37
  • 3
    @JuanDelaCruz You cannot, and you absolutely do not need to. – Bergi Oct 13 '17 at 13:38
  • Just to be clear, using a function expression is what makes it circular right? If I am to use a function definition without bind: `function recursive(){ recursive(); }` it wouldn't be circular? – Juan Dela Cruz Oct 13 '17 at 14:29
  • No, whenever a function refers to itself recursively there *must* be a circular reference somewhere, and it's the same for a function declaration. Why do you want to avoid this? – Bergi Oct 13 '17 at 14:36
  • Not really avoid, but I want to fully understand the concept and the nuances. – Juan Dela Cruz Oct 13 '17 at 14:43