[英]Deciding when global variable should be inside the function or outside the function
Is the only good reason to have the const declaration that is commented out in the function block rather than at the top of the file is so that is only available to that function and so that the thing can be targeted later out of the function? 在函数块中而不是在文件顶部注释掉const声明的唯一好理由是,它仅可用于该函数,以便以后可以将其作为函数的目标? what is a good way to decide which variables you should put in the function and which ones you shouldnt? 有什么好的方法来决定应将哪些变量放入函数中以及不应将哪些变量放入函数中?
const form = document.getElementById("registrar") ; const input = form.querySelector("input") ; //const submitButton = form.querySelector("button") ; Wasnt needed const invitedList = document.getElementById("invitedList") ; form.addEventListener("submit", (event) => { // const invitedList = document.getElementById("invitedList") ; event.preventDefault() ; const text = input.value ; li = document.createElement("li") ; li.textContent = text ; invitedList.appendChild(li) ; }) ;
On one hand, storing the result of the document.getElementById("invitedList")
computation is performance-wise better than repeating it every time the 'submit' handler is called. 一方面,存储document.getElementById("invitedList")
计算的结果在性能上比每次调用“提交”处理程序都重复进行计算要好。 Here, though, it won't make any observable difference, I wouldn't expect the same form being submitted often (or even more than once, usually) in the page's entire life cycle. 不过,在这里,这没有什么明显的不同,我不希望在页面的整个生命周期中经常(甚至通常不止一次)提交相同的表单。 But that's something to keep in mind. 但这是要牢记的。
On the other hand, what doesn't need to be a global variable, probably shouldn't be a global variable. 另一方面, 不必是全局变量,也可以不应该是全局变量。
In your example, both ways are fine. 在您的示例中,两种方法都很好。 You can argue that you don't want to needlessly repeat the same computation that will yield the same result, and you can argue that you want to move whatever you can to function local scopes, instead of keeping them in the global scope. 您可以辩称,您不想不必要地重复将产生相同结果的相同计算,并且可以辩称,您想移动任何可以作用于局部范围的方法,而不是将它们保留在全局范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.