避免Js全局变量污染

时间:2020-05-01

方式一,定义全局变量命名空间

<script>
    let J = {
        name:'wyzda',
        age:28,
        eat:function () {
            console.log('eat');
        }
    };

    console.log(J.name);
    console.log(J.age + 10);
    J.eat();
</script>

方式二,匿名函数

<script>
    (function () {
        let name = 'wyzda';
        let age = 28;

        function eat() {
            console.log('eat');
        }

        console.log(name);
        console.log(age);
        window.eat = eat;
    })();

    let name = 'test';
    let age = 23;
    console.log(name);
    console.log(age);
    eat();
</script>