JavaScript prevents variable global pollution

Source: Internet
Author: User

前段时间封装了一个函数,当时考虑的没那么多,最近回头看这个封装的函数时发现其实造成了全局污染。原先的函数是这样的:
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)

The code above simulates the SetInterval method and outputs the result as

From the above results you can know that window added FN variable, the reason is also very simple, we call the interval function instead of new, the function of this point is the window, so the idea is very simple to modify, the code is as follows:

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

My solution is to limit all variables to the interval function.

JavaScript prevents variable global pollution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.