为什么window.data工作,而不是数据 [英] why does window.data work and not data

查看:566
本文介绍了为什么window.data工作,而不是数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文件,在一个全局变量数据被定义的主体的最后有一些内联JavaScript。头文件中包含JavaScript文件,JavaScript文件中的一个函数使用变量中的值。



由于该文件在定义变量,JavaScript文件中的变量返回undefined。但是window.variable返回变量。是否有任何一般规则我失踪或这只是在我的情况巧合。

HTML简化:

 < script src ='myFile.js'language ='JavaScript'type ='text / javascript'>< / script> 
< script language =javascript>
var inLine =abcde;
< / script>

不起作用的myFile.js(返回undeline inline):

  var insideFile = inLine.length; 

可以工作的myFile.js:

  var insideFile = window.inLine.length; 

总而言之,我想知道为什么其中一个可以工作,而不是另一个。

解决方案

在定义变量之前包含了js文件,这意味着文件中的代码在定义该变量之前运行,因此您会收到错误消息。 p>

你不会因为 window.varname 而错误的原因也是你不会因此而出错的原因:

  var obj = {}; 
console.log(obj.a);

当您在对象上查找属性并且它不存在时,Javascript显示为未定义。


I have an html file that has some inline JavaScript in the end of the body where a global variable data is defined. A JavaScript file is included in the head, and one of the functions inside the JavaScript file uses the value in the variable.

Since the file was included before the definition of the variable, the variable in the JavaScript file is returning undefined. but window.variable returns the variable. Is there any general rule I'm missing or this is just a coincidence in my case.

HTML simplified:

<script src='myFile.js' language='JavaScript' type='text/javascript'></script>
<script language="javascript">
    var inLine = "abcde"; 
</script>

myFile.js that does not work (returns undefine inLine):

var insideFile = inLine.length;

myFile.js that works:

var insideFile = window.inLine.length;

In sum I want to know why one of them works and not the other

解决方案

Your js file is included before variable is defined and which means code inside the file runs before this variable is defined, So you get the error.

The reason you dont get error for window.varname is also the reason you wont get error for this:

var obj = {};
console.log(obj.a);

when you look up property on object and it doesnt exists Javascript shows undefined.

这篇关于为什么window.data工作,而不是数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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