Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Named Access on Window Object is bad practice? #1

Open
SaintPeter opened this issue Mar 29, 2020 · 0 comments
Open

Named Access on Window Object is bad practice? #1

SaintPeter opened this issue Mar 29, 2020 · 0 comments

Comments

@SaintPeter
Copy link

I was reviewing your article on building a vanilla JS router on Free Code Camp's news, when I ran across this code:

      window.onload = event => {
            // Add history push() event when boxes are clicked
            window["home"].addEventListener("click", event => push(event))
            window["about"].addEventListener("click", event => push(event))
            window["gallery"].addEventListener("click", event => push(event))
            window["contact"].addEventListener("click", event => push(event))
            window["help"].addEventListener("click", event => push(event))
        }

I was confused, since I'd never seen this access of the window object. About 20 minutes of googling later led me to these two Stack Overflow responses:
https://stackoverflow.com/a/3434388/1420506
https://stackoverflow.com/a/11691401/1420506

Both conclude that using named access on the Window object should probably be avoided in preference to document.getElementById(). As I understand the reasoning, it is possible or even likely to get name collisions in the global window namespace which will result in unexpected behavior. For example, if you chose an element id which overlapped with an existing/reserved global/window property (IE: windows.closed or window.event), your router event would not be attached and would not fire.

I believe this is a bad practice, used without proper explanation in your code, and should not be included in a Free Code Camp article named at coding novices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant