understanding the javascript global namespace and closures

前端 未结 4 1261
闹比i
闹比i 2020-12-04 15:49

I\'m trying to improve my understanding of the global namespace in javascript and I\'m curious about a few things:

  1. is there a \"GOD\" (i.e. a parent) object

4条回答
  •  北海茫月
    2020-12-04 16:29

    If you NEED to put variables in the global namespace, and you likely will at some point, create a single object variable and add your other variables to it as properties or methods. Give the object a name that is not likely to be used by anyone else (admittedly, this is where collision problems arise, but that can be mitigated by careful, standardized naming).

    e.g. Instead of:

    var thing1 = 'table';
    var anotherthing = 'chair';
    var mypet = 'dog';
    var count = 4;
    var show_something: function( _txt ) { return _txt.trim(); };
    

    Do this:

    var cmjaimet_obj = {
      thing1: 'table',
      anotherthing: 'chair',
      mypet: 'dog',
      count: 4,
      show_something: function( _txt ) { return _txt.trim(); }
    };
    

    Then later call them as properties:

    e.g. Instead of:

    count += 2;
    anotherthing = 'sofa';
    console.log( show_something( 'Thing: ' + anotherthing ) );
    

    Do this:

    cmjaimet_obj.count += 2;
    cmjaimet_obj.anotherthing = 'sofa';
    console.log( cmjaimet_obj.show_something( 'Thing: ' + cmjaimet_obj.anotherthing ) );
    

提交回复
热议问题