Question about Javascript - from Typescript 3.1 - classes.


#1

Typescript lesson 3.1 (classes),

Jeremy adds a new property to the Point class:

static origin = new Point(0, 0);

I’m wondering why this line doesn’t result in an infinite amount of object creation. Even without static it seems to work. How does javascript avoid this? I would have thought that this would make each point object create a new point object, which would in turn create another point object and so on.

Thank you


#2

Well, with the static keyword it all makes sense. The static origin member is attached to the Point class instead of any particular instance of the class, so new Point() is evaluated when the class is defined - just once.

Without the static keyword, it’s true that there should be an infinite amount of object creation at runtime. I tested this with the TypeScript Playground and found this to be the case. There was no compile-time error, but at runtime I got a Uncaught RangeError: Maximum call stack size exceeded exception - which basically means too much recursion.

I found it helpful to look at the emitted JS (again, using the TypeScript Playground).

class TestOkay {
    static recursive = new TestOkay()
}

compiles to

var TestOkay = (function () {
    function TestOkay() {}
    TestOkay.recursive = new TestOkay();
    return TestOkay;
}());

So you can see that the recursive static member is initialized right away in the immediately-invoked function. However,

class TestWrong {
    recursive = new TestWrong()
}

compiles to

var TestWrong = (function () {
    function TestWrong() {
        this.recursive = new TestWrong();
    }
    return TestWrong;
}());

and you can see that the recursive member is initialized in the class constructor, which calls the class constructor… Stack overflow!