Learning by sharing


The Window.self read-only property returns the window itself, as a WindowProxy. It can be used with dot notation on a window object (that is, window.self) or standalone (self). The advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in Web Workers. By using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to WorkerGlobalScope.self).
简单地说,self 实际上就是指向于 window ,本质上下面几种都是严格相等的:
var w1 = window;
var w2 = self;
var w3 = window.self;
var w4 = window.window;
self 更多的是用在不同的上下文环境中用来指向于 window 变量的。比如直接在 window 上下文环境中调用 self ,实际上会解析到 window.self 。而在 service worker 里面,则会解析到 WorkerGlobalScope.self 。因此,在 service worker 的上下文环境中,就可以通过 self 变量来引用 window 变量。直接引用 window 变量会报错。于是上面的几个例子里面,在 service worker 环境中,只有 w2 变量能够正常工作。