How to create private variable accessible to Prototype function?

前端 未结 4 1361
陌清茗
陌清茗 2020-12-08 01:35

I\'m trying to get a deeper hold on prototypal inheritance and class creation (I know, there are other ways, but for the purpose of this I\'m trying to grasp prototypes.) My

4条回答
  •  半阙折子戏
    2020-12-08 01:54

    This is what I wrote about in a blog post about Classes, Private Members, & Prototypal Inheritance in JavaScript. Basically you want to create a private variable accessor function unique to every object and then have those prototype methods call that private accessor function, supplying it with the key that is only available within the closure:

    (function(_) {
      Tree = function ( name, size ) { 
        var hidden = {
          name: name,
          size: size
        };
        this._ = function($) {
          return _ === $ && hidden;
        };
      };
    
      Tree.prototype.genus = function(){
        return ((typeof this._(_).name !== 'undefined') ? this._(_).name : 'Hybridicus Maximus');
      };
      Tree.prototype.bulk = function(){
        return ((typeof this._(_).size !== 'undefined') ? this._(_).size : '8') + ' ft';
      };
    
      Fruit = function( name, size ) { 
        Tree.apply(this, arguments);
      };
      Fruit.prototype = new Tree();
      // Fruit.prototype = Tree.prototype; -- I know this can be used, too.
    
      Fruit.prototype.bulk =  function(){
        return ((typeof this._(_).size !== 'undefined') ? Math.floor(this._(_).size / 2) : '4') + ' lbs';
      };
    })({});
    
    
    
    var pine = new Tree('Pine', 9);
    var apple = new Fruit('Apple', 6);
    
    console.log(pine.genus(), pine.bulk()); // Outputs: "Pine 9 ft"
    console.log(apple.genus(), apple.bulk()); // Outputs: "Apple 3 lbs"
    
    console.log(pine._(), pine._({})); // Outputs: "false false" because outside of closure
    

    You will notice that the last line shows that private variables are not accessible outside of the closure and thusly can't be retrieved by third-party code unless made available by an accessor function.

提交回复
热议问题