elements exist as properties on the window
This question already has an answer here:
I am not sure about the historical perspective, but HTML 5 specifies that elements are candidates to be directly exposed as properties on the window
object if they have an id
attribute:
The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:
[...]
The problem with this definition is that it only guarantees that if there is a <div id="foo">Foo<div>
then window.foo
will be defined. It does not guarantee what exactly its value will be (read the spec for the rules on how that is determined; for example, it might return a collection).
So it turns out the answer to "why use getElementById
ever?" is simple: because you can depend on it to return what you expect without needing to take into account the whole document.
In general placing something inside the window object will make it global. For example:
var A = function() {
window.test = "bla";
console.log(test);
}
var B = function() {
console.log(test);
}
A();
B();
However that's not a good practice. You should not rely on any global object, because you may want to move your code to a browser that doesn't have window. Or to nodejs for example.
I find window.foo a little bit wrong, because you may have code that creates a global variable called foo. So, using getElementById ensures you that you always get DOM element.
Window.foo is working fine in your scenario, but what if the Id is something like this "foo-test" instead of "foo", you can see it will not work. it is because Javascript variables are not allowed for dashes in it.... Whereas it will work fine in case of document.getElementById
链接地址: http://www.djcxy.com/p/74114.html上一篇: 在R中的大数据集上运行回归树
下一篇: 元素作为窗口上的属性存在