简体   繁体   中英

Using functions only to reference DOM elements

I am learning JS from a book and the author constantly uses functions to reference DOM elements like this:

const navItems = () => document.querySelectorAll("nav li");

Why does he not just declare a variable like this:

const navItems = document.querySelectorAll("nav li");

In my experience so far it makes little difference in the code, only that you have to call the functions by using the parentheses. Is the first one considered better style for some reason?

const navItems = () => document.querySelectorAll("nav li");

navItems is a function and you would call it like navItems() whenever you want to get the elements.

const navItems = document.querySelectorAll("nav li");

navItems here is a variable and this would not return live count if any li item is added after it's defined.

In sites that maintain the same content, there would be no difference between the two. However, in more complicated sites that might add elements dynamically after the page is loaded, the first approach would have the updated values while the second would not. The first would only be better style if new elements are added.

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