Javascript private member on prototype

前端 未结 8 942
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 01:15

Well I tried to figure out is this possible in any way. Here is code:

a=function(text)
{
   var b=text;
   if (!arguments.callee.prototype.get)
      argumen         


        
8条回答
  •  盖世英雄少女心
    2020-12-08 01:44

    I think real privacy is overrated. Virtual privacy is all that is needed. I think the use of _privateIdentifier is a step in the right direction but not far enough because you're still presented with a listing of all the _privateIdentifiers in intellisense popups. A further and better step is to create an object in the prototype and/or constructor function for segregating your virtually private fields and methods out of sight like so:

      // Create the object
      function MyObject() {}
    
      // Add methods to the prototype
      MyObject.prototype = {
    
        // This is our public method
        public: function () {
          console.log('PUBLIC method has been called');
        },
    
        // This is our private method tucked away inside a nested privacy object called x
        x: {
          private: function () {
            console.log('PRIVATE method has been called');
          }
        },
    
      }
    
    // Create an instance of the object
    var mo = new MyObject(); 
    

    now when the coder types "mo." intellisense will only show the public function and "x". So all the private members are not shown but hidden behind "x" making it more unlikely for a coder to accidentally call a private member because they'll have to go out of their way and type "mo.x." to see private members. This method also avoids the intellisense listing from being cluttered with multiple private member names, hiding them all behind the single item "x".

提交回复
热议问题