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

查看:95
本文介绍了我可以使用ID作为变量名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现设置与元素ID相同名称的变量很方便,例如:

I find it convenient to set a variable with the same name as an element's id, for example:

randomDiv = document.getElementById("randomDiv");
  randomDiv.onclick = function(){ /* Whatever; */ }
  randomDiv.property = "value";

这在Chrome和Firefox中有效,但不适用于IE8;给出错误对象不支持此属性或方法.

This works in Chrome and Firefox, but not IE8; giving the error Object doesn't support this property or method.

使用与元素ID匹配的名称创建变量是错误的(或不良做法),还是Internet Explorer的另一个实例起作用了?

Is creating a variable with a name that matches an element ID wrong (or bad practice) or is this another instance of Internet Explorer acting up?

推荐答案

自动创建全局变量被认为是不正确的做法,因为在查看某些代码时很难分辨出它是否是故意的或者您忘记在某个地方声明变量.像这样的全局变量的自动创建在ES5严格中不起作用模式,并且可以在以后的ECMAScript版本中逐步淘汰.

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.

在浏览器中 JavaScript的全局范围实际上是 window .当您引用 document 时,您将获得 window.document .在浏览器中创建全局变量的最佳实践是将其添加到 window (在Node.js中为 global ).这是来自jQuery的示例:

In the browser JavaScript’s global scope is actually window. When you refer to document you get window.document. Best practice for creating a global variable in a browser is to add it to window (global in Node.js). Here’s an example from jQuery:

window.jQuery = window.$ = jQuery;

窗口上的某些属性(因此有一些全局变量)是只读的,您不能覆盖它们. window.document 是其中之一(在Chrome中进行了测试,这是所有特定于浏览器的,并且可能会更改):

Some properties on window (hence some global variables) are read-only, you can’t overwrite them. window.document is one (tested in Chrome, this is all browser-specific and could change):

window.document; // → Document
window.document = 'foo'; // → "foo" // It worked!
window.document; // → Document // Hmm, no it didn’t

事实证明,大​​多数浏览器在 window (因此是全局变量)上为文档中的每个ID创建属性.许多浏览器都不将其设为只读,您可以使用自己的浏览器将其覆盖,而Internet Explorer可以将其覆盖.

It turns out that most browsers create properties on window (hence global variables) for each id in the document. Many browsers don’t make them read-only, you can overwrite them with your own, but Internet Explorer does.

这是JavaScript中的全局变量可能很危险的另一个原因-您的一个ID可能与只读的 window 属性(今天或将来使用的浏览器)相匹配.

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).

在顶层(不在函数内), var 声明全局变量.在顶层声明 var document ='foo'不会引发错误,但是 document 仍将是 Document ,而不是"foo" .

At the top level (not inside a function), var declares global variables. Stating var document = 'foo' at the top level won’t throw an error but document will still be the Document, not "foo".

顺便说一句:新颖的浏览器(支持ES5)使您可以使用 Object.defineProperty 创建自己的只读全局变量:

As an aside: new-ish browsers (which support ES5) let you create your own read-only globals with Object.defineProperty:

Object.defineProperty(window, 'foo', { value: 'bar', writable: false });
foo = 'baz';
foo; // → "bar"


我为您提供了三种选择.


I’ve got three options for you.

  1. 继续为元素使用全局变量,但如果它们已经存在则将其保留(在 window 上显式创建它们,以便使用ES5编写清晰的代码):

  1. Keep using global variables for your elements but leave them alone if they already exist (creating them on window explicitly so the code is clear and cool with ES5):

if ( ! window.randomDiv) {
    window.randomDiv = document.getElementById('randomDiv');
}

  • window 上创建一个对象,以用作应用程序自己的名称空间,该名称空间不会干扰其他库或浏览器.这很普遍,被认为是很好的做法,尤其是在需要跨JavaScript文件访问的情况下.

  • Create an object, on window, to use as your app’s own namespace which won’t interfere with other libraries or with the browser. This is common and considered pretty good practice, especially if it needs to be accessed across JavaScript files:

    // Early in your code…
    window.Fantabulum = {};
    // Later on…
    Fantabulum.randomDiv = document.getElementById("randomDiv");
    

  • 避免创建全局变量.确保您的应用程序代码位于函数内部(应该已经在其中,因此您的其他变量不是全局变量,并且没有相同的限制!),然后为元素声明变量:

  • Avoid making globals. Make sure that your application’s code is inside a function (it should be already so your other variables aren’t global and don’t have the same limitations!), and declare variables for your elements:

    (function(){
        var randomDiv = document.getElementById("randomDiv");
    })();
    

  • 这篇关于我可以使用ID作为变量名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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