全局变量和窗口对象的属性有什么区别? [英] What is the difference between a global variables and attributes of the window object?

查看:108
本文介绍了全局变量和窗口对象的属性有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript的窗口对象感到有点困惑。对于初学者,请考虑以下两个声明:

I'm a bit confused by JavaScript's window object. For starters, consider the following two declarations:

var imglobal = "I'm Global";

window.imglobal = "I'm Global";

据我了解,这将完全相同(是吗?)它可以是在两种情况下都被访问为imglobal或window.imglobal。我不明白为什么,var声明本地变量,以下不起作用:

As far as I understand it, this would be exactly the same (is it?) It can be accessed as "imglobal" or "window.imglobal" in both cases. I don't understand why, var declares local variables, the following doesn't work:

function imafunc() {
  var imavar = "I'm a variable";
  window.alert(imafunc.imavar);
}

那么为什么会出现以下情况?

So why does the following?

var imavar = "I'm a variable";
window.alert(window.imavar);

我在使用GWT时遇到了这个问题;它似乎总是必须在那里明确地引用窗口对象($ wnd),可能是因为它不是真正的窗口对象而是某种沙盒。

I stumbled across this when using GWT; it appears one always has to refer to the window object ($wnd there) explicitly there, probably because it's not the "real" window object but some kind of sandbox.

它让函数更加混乱,我知道三种方式来声明它们:

It gets even more confusing with functions, I know three ways to declare them:

var myfunc = function() { window.alert("Hello, World!"); }

window.myfunc = function() { window.alert("Hello, World!"); }

function myfunc() { window.alert("Hello, World!"); }

这三种方法之间是否存在技术差异?

Is there any technical difference between these three approaches?

推荐答案

关于你的观察:


我在使用GWT时偶然发现了这一点;它似乎总是必须在那里明确地引用窗口对象($ wnd),可能是因为它不是真正的窗口对象而是某种沙盒。

I stumbled across this when using GWT; it appears one always has to refer to the window object ($wnd there) explicitly there, probably because it's not the "real" window object but some kind of sandbox.

你总是需要在GWT JSNI中使用$ wnd为变量和函数添加前缀的原因是确保从窗口范围(主页)访问变量。这是因为JSNI在iframe中运行,因此没有$ wnd限定符的任何变量都将在iframe的范围内解析,而不是你想要的窗口范围。

The reason you will always need to prefix your variables and functions with $wnd in GWT JSNI is to ensure that you are accessing the variable from the window scope (host page). This is because JSNI is run inside an iframe, hence any variable without the $wnd qualifier would resolve within the scope of the iframe and not the window scope, which you intended.

这篇关于全局变量和窗口对象的属性有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆