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方法,输出结果为
javascript防止变量全局污染

创新互联公司专注于建瓯企业网站建设,响应式网站设计,商城网站建设。建瓯网站建设公司,为建瓯等地区提供建站服务。全流程按需规划网站,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

从上述结果看便可知道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)   //报错,未定义temp
console.log(fn)     //报错,未定义fn

我的解决思路就是将所有的变量限制在interval函数内。


本文名称:javascript防止变量全局污染
标题链接:http://scjbc.cn/article/jphdgs.html

其他资讯