简体   繁体   English

我应该使用self或window来引用全局范围吗?

[英]Should I use self or window to reference the global scope?

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. 我现在有一个可以直接从浏览器使用的模块,或者,如果它们可用,则来自Web工作者。 In web workers the global object is called self , while in the browser it's called window . 在Web worker中,全局对象称为self ,而在浏览器中称为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 ). window对象具有self属性,因此self.example = "Hello"在两个上下文中都可以工作,只要没有人重新声明self (就像他们经常做的那样: var self = this )。

What's the best convention to go with? 什么是最好的约定?

  • Use self and hope no-one declares a conflicting self . 使用self和希望没有人宣称冲突的self
  • If window is defined, use window , otherwise use self . 如果定义了window ,请使用window ,否则使用self
  • Something else? 别的什么?

Having thought about it, I'm inclined to go with the second one. 想到这一点,我倾向于选择第二个。

In the global scope, either in the page or a web worker, you can write code like this: 在全局范围内,无论是在页面还是Web工作者中,您都可以编写如下代码:

(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). 然后在主外部函数内部,您可以使用“global”(或称之为“window”或“self”或“whatever”),它可以在任一上下文中工作(或者在Node.js中工作)。

我建议

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

您可以创建自己的窗口或自我引用:

var my_window = window || self;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM