Javascript继承无限循环 [英] Javascript inheritance infinite loop

查看:47
本文介绍了Javascript继承无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中创建了这段代码:

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

I don't know why but when I run it, firefox is freeze. I've been trying hours to figure it out. And my guess is there should be an infinite loops in my code and it lives somewhere in the if condition, but I didn't find it out. Could someone help me out of this headache. Thank you!

推荐答案

当你打电话给 this.constructor.uber.toString() 来自 Shape.prototype.toString uber twoDShape。原型这是一个 Shape ,所以 toString 方法是 Shape.prototype.toString 再次。

When you call this.constructor.uber.toString() from Shape.prototype.toString, uber is twoDShape.prototype which is a Shape, and so that toString method is Shape.prototype.toString again.

这会导致无限循环。

这篇关于Javascript继承无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆