最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should I use self or window to reference the global scope? - Stack Overflow

programmeradmin1浏览0评论

As a style convention I like to be explicit when I'm accessing variables in the global scope, preferring

window.example = "Hello";
window.alert(window.example);

to the less verbose

example = "Hello";
alert(example);

I now have a module which could be used directly from the browser, or, if they're available, from a web worker. In web workers the global object is called self, while in the browser it's called window.

The window object has a self property, so self.example = "Hello" would work in both contexts, so long as no-one redeclares self (as they often do: var self = this).

What's the best convention to go with?

  • Use self and hope no-one declares a conflicting self.
  • If window is defined, use window, otherwise use self.
  • Something else?

Having thought about it, I'm inclined to go with the second one.

As a style convention I like to be explicit when I'm accessing variables in the global scope, preferring

window.example = "Hello";
window.alert(window.example);

to the less verbose

example = "Hello";
alert(example);

I now have a module which could be used directly from the browser, or, if they're available, from a web worker. In web workers the global object is called self, while in the browser it's called window.

The window object has a self property, so self.example = "Hello" would work in both contexts, so long as no-one redeclares self (as they often do: var self = this).

What's the best convention to go with?

  • Use self and hope no-one declares a conflicting self.
  • If window is defined, use window, otherwise use self.
  • Something else?

Having thought about it, I'm inclined to go with the second one.

Share Improve this question edited May 23, 2017 at 12:27 CommunityBot 11 silver badge asked Jun 22, 2012 at 18:24 RichardTowersRichardTowers 4,7721 gold badge28 silver badges43 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

In the global scope, either in the page or a web worker, you can write code like this:

(function( global ) {
  // ... whatever
}( this );

Then inside that main outer function you can use "global" (or call it "window" or "self" or "whatever") and it'll work in either context (or in Node.js for that matter).

I'd suggest

var global; try { global = window } catch(e) { global = self }

You could create your own reference to either window or self:

var my_window = window || self;
发布评论

评论列表(0)

  1. 暂无评论