gpt4 book ai didi

Javascript继承无限循环

转载 作者:搜寻专家 更新时间:2023-11-01 04:33:03 25 4
gpt4 key购买 nike

我在 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() 时,ubertwoDShape。 prototype 是一个 Shape,因此 toString 方法又是 Shape.prototype.toString

这会导致无限循环。

关于Javascript继承无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12970308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com