5

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

well, after trying a fair amount of test, I finally got a clue. And I believe this is a answer for my own question above. Typing: a.constructor.uber.constructor === twoDShape in firefox, it returns true. And that's why it causes infinite loop.

1 Comment

To be accurate, it's looping in the toString method as per my above answer. The constructors being the same are why this is happening (method calling itself) but isn't actually the cause of the loop in itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.