前段时间封装了一个函数,当时考虑的没那么多,最近回头看这个封装的函数时发现其实造成了全局污染。原先的函数是这样的:
function interval(fn, ms){ !this.fn?(this.fn = fn,this.ms = ms,this.step = 0):null this.step++ this.step%(this.ms * 60) == 0?this.fn():null requestAnimationFrame(interval)}interval(() => { console.log(1)},1)console.log(fn)
The code above simulates the SetInterval method and outputs the result as
From the above results you can know that window added FN variable, the reason is also very simple, we call the interval function instead of new, the function of this point is the window, so the idea is very simple to modify, the code is as follows:
function interval(fn, ms){ function temp (){ !this.fn?(this.fn = fn,this.ms = ms,this.step = 0):null this.step++ this.step%(this.ms * 60) == 0?this.fn():null requestAnimationFrame(temp) } new temp()}interval(() => { console.log(1)},1)console.log(temp) //报错,未定义tempconsole.log(fn) //报错,未定义fn
My solution is to limit all variables to the interval function.
JavaScript prevents variable global pollution