繁体   English   中英

Javascript继承无限循环

[英]Javascript inheritance infinite loop

我在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条件的某个地方,但我没有找到它。 有人可以帮我解决这个问题。 谢谢!

当你从Shape.prototype.toString调用this.constructor.uber.toString()时, uber是一个Shape twoDShape.prototype Shape ,因此toString方法再次是Shape.prototype.toString

这会导致无限循环。

好吧,经过大量的测试,我终于得到了一个线索。 我相信这是我上面提出的问题的答案。 在firefox中键入:a.constructor.uber.constructor === twoDShape,它返回true。 这就是它导致无限循环的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM