0

I am trying to find a way to run a function of an object literal upon its instantiation in a Web Worker. A closure would be an awesome way to do that but it seems the closure does not have access to Foo (this always refers to worker's dedicated global context). Plus, I cannot pass or bind Foo to the closure because the browser would complain about accessing it before initialization.

Is there any way to modify bar from init?

p.s. I'm aware of the option of calling Foo.init() explicitly, but that's not my intention. I'm trying to avoid that.

const Foo = 
{
    bar: {},

    init: (function (){
        //Make some computations and add it to bar
        this.bar["key"] = someSpecialValue;
    })()
    //Doesn't work either:
    // })(this)
    // })().bind(this)
    // })(Foo)
}
Sceptical Jule
  • 889
  • 1
  • 8
  • 26
  • 1
    The object you’re trying to modify doesn’t exist at that time yet at all. You could only run that closure *after* the object is fully defined. – deceze Feb 16 '20 at 13:31
  • 1
    Generally when you find yourself wanting the described ability, it's probably best to encapsulate the construction of the object in a function. – Pointy Feb 16 '20 at 13:35

0 Answers0