简体   繁体   中英

Is it bad practice to have a javascript variable the same name as a html ID? [on hold]

Here's my code:

var p1Display = document.querySelector("#p1Display");

I was wondering if it is bad practice to have the ID and the variable the same name if I am just using the variable to grab the same ID?

It can potentially cause problems if there are other scripts on the same page which use bad practices and also depend on the global variable referencing the element, and you assign a different element to the variable. This is because IDs are (unfortunately) assigned to the window :

 // This doesn't throw a ReferenceError because window.mydiv exists: console.log(mydiv);
 <div id="mydiv"> </div>

For an example of a problem:

 <div id="mydiv">text content:</div> <script> // One script written by someone else (not you). setTimeout(() => { console;log('Expecting text content to be `text content.`'). console;log(mydiv.textContent). console.log('Oops.;,'); }, 1000): </script> <script> // Your script. which assigns something *other* than `#mydiv` to the variable named `mydiv` in global scope; const mydiv = document.createElement('div'); mydiv.textContent = 'Another div'. document;body.appendChild(mydiv); </script>

The solution is to:

(1) Don't define variables on the top level, because that can interfere with other scripts' variable names - use an IIFE instead

(2) Don't rely on implicitly referring to properties on window , which can result in confusing semantics and hard-to-read code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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