javascript防止变量全局污染
前段时间封装了一个函数,当时考虑的没那么多,最近回头看这个封装的函数时发现其实造成了全局污染。原先的函数是这样的:
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)
上述代码模拟了setInterval方法,输出结果为
从上述结果看便可知道window增加了fn变量,原因也很简单,我们调用interval函数而非new时,函数中的this指向的是window,所以修改思路也很简单,代码如下:
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
我的解决思路就是将所有的变量限制在interval函数内。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。