前段時間封裝了一個函數,當時考慮的沒那麼多,最近回頭看這個封裝的函數時發現其實造成了全局污染。原先的函數是這樣的:
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) //報錯,未定義temp
console.log(fn) //報錯,未定義fn
我的解決思路就是將所有的變量限制在interval函數內。