search

Home  >  Q&A  >  body text

How to get the global variable of an element to avoid being polluted?

var ele=document.getElementById('btn');
When writing native js, you need to obtain a large number of page elements. Now that there are too many global variables, how do you avoid being polluted?

曾经蜡笔没有小新曾经蜡笔没有小新2789 days ago615

reply all(4)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:13:18

    Open namespace:
    var name={};
    name.common={};
    name.fx={};
    name.site={};
    name.common.ele1= document.getElementById('btn' );
    neme.fx.ele1= document.getElementById('btn2');

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:13:18

    Wrap it in IIFE and don’t put it globally.

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:13:18

    Same upstairs, wrap one floor with IIFE

    (function () {
        var foo = '...';
        var baar = '...';
    })();

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:13:18

    Modular. requirejs/webpack/ES6 modules, variables are all private to the module.

    reply
    0
  • Cancelreply