2012-10-19 91 views
5

我在JavaScript创建的代码块:Javascript继承无限循环

function Shape() {} 
Shape.prototype.name = "Shape"; 
Shape.prototype.toString = function() { 
    result = []; 
    if(this.constructor.uber) { 
     result[result.length] = this.constructor.uber.toString(); 
    } 
    result[result.length] = this.name; 
    return result.join(', '); 
} 


function twoDShape() {}; 
twoDShape.prototype = new Shape(); 
twoDShape.prototype.constructor = twoDShape; 

twoDShape.uber = twoDShape.prototype; 
twoDShape.name = "twoD Shape"; 

var a = new twoDShape(); 
console.log(a.toString()); 

我不知道为什么,但是当我运行它,Firefox是冻结做。我一直在努力想出来。我的猜测是在我的代码中应该有一个无限循环,它在if条件中存在,但我没有发现它。有人能帮助我摆脱这种头痛。 谢谢!

回答

2

当你调用从Shape.prototype.toStringthis.constructor.uber.toString()ubertwoDShape.prototype这是一个Shape,并让toString方法又是Shape.prototype.toString

而且会导致无限循环。

0

好吧,经过相当数量的测试后,我终于有了线索。我相信这是上面我自己的问题的答案。键入:a.constructor.uber.constructor ===在Firefox中使用twoDShape,它返回true。这就是它导致无限循环的原因。

+0

为了准确,按照我上面的回答,它在toString方法中循环。构造函数是相同的,这就是为什么会发生这种情况(方法调用自己),但实际上并不是循环本身的原因。 – sync