2

There is a class test which has method addRecursively() which has child function (is this the correct term btw?) childFunc() which in turn calls addRecursively()

class Test {

     addRecursively = function (i) {
        i++;
        childFunc();

        function childFunc(){
            if (i==5) {
                console.log(i);
            } else {
                console.log("Not yet");
                this.addRecursively(i); // Cannot read property 'addRecursively' of undefined
            }
        }
    }
}

var testObj = new Test();
testObj.addRecursively(0);

How do I call the parent function without explicily addressing testObj exemplar?

Igor Cheglakov
  • 525
  • 5
  • 11
  • 1
    Make `childFunc` an arrow function. – Maheer Ali May 18 '19 at 15:46
  • 1
    what should happen if you call the function? `i` never change inside. – Nina Scholz May 18 '19 at 15:48
  • 1
    you could just exclude your function from the object `` – DigitalJedi May 18 '19 at 15:48
  • 1
    What is this program trying to accomplish? `this` is not bound to the nested function, so it's undefined. – ggorlen May 18 '19 at 15:50
  • 1
    Actually the nested function is a normal function and it doesn't use the lexical `this` means the `this` inside the `childFunc` is not same as `this` in `addRecursively`.If you want to use `this` of parent inside nested function then use Arrow Function. Here https://jsfiddle.net/maheerali121/typ7g6m9/1/ I have created a fiddle that works fine. – Maheer Ali May 18 '19 at 15:53
  • @ggorlen It's supposed to `i++` until `i==5` and `then console.log(i);` Just a simple demonstration of the problem. – Igor Cheglakov May 18 '19 at 15:54
  • You can also do this instead of arrow function: `childFunc.bind(this)`; – maaajo May 18 '19 at 16:14

0 Answers0