How to create public and private members?

前端 未结 6 1833
小鲜肉
小鲜肉 2020-12-17 03:22

I\'m a bit confused, how can I create public and private members.

My code template so far is like:

(function()){
   var _blah = 1;

   someFunction =         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 03:37

    Three things:

    1. IIFEs:
      It seems like you need to refresh your knowledge regarding this pattern. Have a look at this post before using an IIFE again.

    2. Global public vs. Safe public:
      Skipping var keyword with someFunction and someOtherFunction leads to registration of these function objects in the global scope, i.e., these functions can be called and reassigned from anywhere in the code. That could lead to some serious bugs as the code grows bigger in size. Instead, as Daniel suggested, use the module pattern. Though you can use other methods too like Constructors, Object.create(), etc, but this is pretty straightforward to implement.

      /* create a module which returns an object containing methods to expose. */
       var someModule = (function() {  
           var _blah = 1;  
            return {  
              someFunction: function() {},  
              someOtherFunction: function() {}  
            };  
       })(); 
      /* access someFunction through someModule */
      someModule.someFunction();
      // ...
      // ....
      /* after 500+ lines in this IIFE */
      /* what if this happens */  
      someFunction = function() {  
          console.log("Global variables rock.");  
      };  
      /* Fortunately, this does not interfere with someModule.someFunction */
      
    3. Convention and scope combined:
      We cannot expect from every developer to follow the underscore or the capitalization convention. What if one of them forgets to implement this technique. Instead of just relying upon the convention (_private, GLOBAL) and the scope (function scoping), we can combine both of them. This helps in maintaining consistency in coding style and provides proper member security. So, if next time somebody forgets to capitalize their globals, the console (in strict mode) can prevent the world from ending.

提交回复
热议问题