简体   繁体   English

JS中未声明的变量自动获取DOM对象

[英]Undeclared variable in JS automatically picking up DOM objects

Look at the following JS code: 看看下面的JS代码:

alert(myImgId.src);

and corresponding HTML: 和相应的HTML:

<img id="myImgId" src="http://images4.wikia.nocookie.net/__cb20121128141533/logopedia/images/6/6f/Superman_logo.png"></img>

What I expect would happen: A javascript error specifying that it cannot find variable myImgId , basically a sort of NPE while accessing object src of myImgId . 我期望会发生什么:一个ja​​vascript错误,指出它无法找到变量myImgId ,在访问myImgId对象src时基本上是一种NPE。

What actually happens: Modern browsers(FF 17 & above, chrome) pick up the DOM element with the given ID automatically. 实际发生的事情:现代浏览器(FF 17及以上版本,chrome)自动获取具有给定ID的DOM元素。 Older versions of browsers like FF 10 throw an error as expected. 较早版本的浏览器(如FF 10)会按预期抛出错误。

Can somebody explain what is happening over here? 有人可以解释一下这里发生了什么吗?

JSFiddle link JSFiddle链接

I gleaned this from another SO question, the question is not really the same as your question, but the answer does answer your question: 我从另一个问题中收集了这个问题,这个问题与你的问题并不完全相同,但答案确实回答了你的问题:

Can I Use an ID as a Variable Name? 我可以使用ID作为变量名吗?

and here is the good stuff: (all quoted from Sidnicious' answer) 这是好东西:(所有引自Sidnicious的回答)

Making global variables automatically is considered bad practice because it can be difficult to tell, looking at some code, whether it is on purpose or you forgot to declare a variable somewhere. 自动生成全局变量被认为是不好的做法,因为它很难分辨,查看某些代码,是否有意或者您忘记在某处声明变量。 Automatic creation of global variables like this doesn't work in ES5 strict mode and could be phased out phased out in future versions of ECMAScript. 像这样自动创建全局变量在ES5严格模式下不起作用,并且可以在ECMAScript的未来版本中逐步淘汰。

In the browser JavaScript's global scope is actually window. 在浏览器中,JavaScript的全局范围实际上是窗口。 When you refer to document you get window.document. 当你引用文档时,你得到window.document。 Best practice for creating a global variable in a browser is to add it to window (global in Node.js).... 在浏览器中创建全局变量的最佳实践是将其添加到窗口(Node.js中的全局变量)....

...It turns out that most browsers create properties on window (hence global variables) for each id in the document. ...事实证明,大多数浏览器为文档中的每个id在窗口(因此全局变量)上创建属性。 Many browsers don't make them read-only, you can overwrite them with your own, but Internet Explorer does. 许多浏览器不会将它们设置为只读,您可以使用自己的浏览器覆盖它们,但Internet Explorer会这样做。

This is another reason global variables in JavaScript can be dangerous — one of your ids could match a read-only window property (today or in some future browser). 这是JavaScript中的全局变量可能存在危险的另一个原因 - 您的一个ID可能与只读窗口属性(今天或将来某个浏览器)相匹配。

My guess is: 我的猜测是:

Since you did not declare the variable with var , it is seen as a global variable (global to the entire window) and the browser is automatically hooking it up, since the ID is the same as the object name. 由于您没有使用var声明变量,因此它被视为全局变量(整个窗口的全局变量),并且浏览器会自动将其挂起,因为ID与对象名称相同。

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

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