js make later get window variable; don't init var until this var is called

Viewed 31

I expect set window variable before its inner class defined, so I make following code

Object.assign(window, {
    get C2() {
        return C
    }
})

class C {

}

new C2()

but it raise Uncaught ReferenceError: Cannot access 'C' before initialization, I know put class C def before Object.assign can fix this err, but my confused is why following code cannot later get

Object.assign(window, {
        get C2() {
            return C
        }
    })
1 Answers

The C class you name is actually referenced as soon as you call Object.assign, the get C2() property that is created contains a reference to C that must be known when Object.assign is called.

If the C class name is not known when Object.assign is called, then JS doesn't know what should be assigned.

Related