I played around with some recursive programming. I have one variable to keep track of my depth (d). The console log is for me to see where the program is at the moment.
var Test = function(){
this.rekursiv = function(d){
this.d = d;
console.log("case 1 granted, d: " + this.d);
if( this.d < 3) {
console.log("going deeper..");
this.rekursiv(this.d + 1);
console.log("going back..");
}
console.log("d: " + this.d );
}
}
t = new Test();
t.rekursiv(0);
Here is my problem: Whenever I go one level deeper, I pass "this.d + 1" to the next level. Howevever, debugging the code (with the console.log) shows that d doesn't only get changed in one level/depth, but in every level/depth.
Why is this so? How can i prevent the code from doing this?
this.disn't a variable. It's a property on an object, which happens to be the same object used as the value ofthisin the recursive call. There's no reason for a separate variable in your code, since you already have thedparameter.function Test(d) { if (d < 3) { console.log(d); Test(d + 1); console.log(d) } else console.log("base case") }. The problem with your function is, that it doesn't return anything. The base case just performs a side effect (console.log).