-Lost said:
I was perusing some code and saw:
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
Is this a waste of code? Or is there some instance where
bracket notation might fail?
Your question betrays some misconception, either as to the nature of
property accessors or about what the code above is attempting.
Bracket notation and dot notation are the two forms of property accessor
available in javascript. Whenever the property names used in either are
literals that would qualify as Identifiers in javascript the two are
completely interchangeable. That is:-
document.forms['aspnetForm']
- may also be written as any of:-
document.forms.aspnetForm
document['forms'].aspnetForm
document['forms']['aspnetForm']
window['document'].forms.aspnetForm
window['document'].forms['aspnetForm']
window['document']['forms'].aspnetForm
window['document']['forms']['aspnetForm']
- to precisely the same effect (though with some very minor differences
in performance).
And similarly:-
document.aspnetForm
- may also be written as:-
document['aspnetForm']
window['document'].aspnetForm
window['document']['aspnetForm']
- to precisely the same effect.
The code above has no interest in any distinction between dot notation
property accessors and bracket notation property accessors, and that
distinction had no relevance for the code.
The question the code is asking is "is there a property of the -
document.forms - collection with the name 'aspnetForm'?", and if not "is
there then instead a property of the - document - with the same name?".
It almost certainly is a waste of code because if you assume that a
property with the name "aspnetForm" is intended to refer to a form
element (the alternative would be to assume the author did not perceive
the sense in giving objects non-misleading names) then there have never
been any browsers where a named form element could not be references as
a named property of the (ancient, and W3C DOM formalised) -
document.forms - collection but could then be referenced through the
common (though non-standard) HTML DOM shortcut of referring to it as a
named property of the - document - object.
Richard.