When to use self in JavaScript

后端 未结 3 1053
夕颜
夕颜 2020-12-08 02:49

I\'ve noticed that calls like setTimeout() work either as :

self.keyword()

or just on their own e.g. keyword().

3条回答
  •  旧时难觅i
    2020-12-08 03:08

    Every property and method on window object can be called with or without 'window.'.

    and

    self is a read-only property on window object that returns the window itself (MDN)

    so

    setTimeout()

    window.setTimeout()

    window.self.setTimeout()

    self.setTimeout()

    are all same thing.

    The main advantage of doing self.setTimeout() instead of window.setTimeout() or any other way is that, if you run some code that calls window.setTimeout() inside WebWorker, it will fail but the self.setTimeout() will work both in web workers and the browser context. So if you are writing a library that should work both on main window's scope and the web worker, we should prefer using self.

    self always refer to the GlobalScope which in case of browser mode is window and inside web workers is `WorkerGlobalScope'

提交回复
热议问题