Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inheritance infinite loop

Tags:

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

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!

like image 584
Lac Viet Avatar asked Nov 04 '22 13:11

Lac Viet


1 Answers

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.

And that causes an infinite loop.

like image 126
sync Avatar answered Nov 12 '22 16:11

sync