我玩了一些递归编程。我有一个变量来跟踪我的深度(d)。控制台日志供我查看程序当前所在的位置。

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);


这是我的问题:
每当我深入一个级别时,我都会将“this.d + 1”传递到下一个级别。
但是,调试代码(使用console.log)显示d不仅会在一个级别/深度上更改,而且会在每个级别/深度上更改。

为什么会这样呢?如何防止代码执行此操作?

最佳答案

为什么不使用局部变量d

使用this.d,您可以设置Test实例的属性。并且随着rekursiv的结尾,您不会将值更改回原来的值。

var Test = function () {
        this.rekursiv = function(d) {
            console.log("case 1 granted, d: " + d);
            if (d < 3) {
                console.log("going deeper..");
                this.rekursiv(d + 1);
                console.log("going back..");
            }
            console.log("d: " + d  );
        }
    },
    t = new Test;

t.rekursiv(0);


另一个解决方案是,在函数this.d的开头增加rekursiv,在函数的结尾减少它。

var Test = function () {
        this.d = 0;
        this.rekursiv = function() {
            this.d++;
            console.log("case 1 granted, d: " + this.d);
            if (this.d < 3)	{
                console.log("going deeper..");
                this.rekursiv();
                console.log("going back..");
            }
            console.log("d: " + this.d  );
            this.d--;
        }
    },
    t = new Test;

    t.rekursiv();

09-25 17:25
查看更多