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函数内。

转载于:https://blog.51cto.com/janwool/2095925

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值