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函數內。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章