Accessing private member variables from prototype-defined functions

前端 未结 25 1248
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  悲&欢浪女
    2020-11-22 15:34

    Yes, it's possible. PPF design pattern just solves this.

    PPF stands for Private Prototype Functions. Basic PPF solves these issues:

    1. Prototype functions get access to private instance data.
    2. Prototype functions can be made private.

    For the first, just:

    1. Put all private instance variables you want to be accessible from prototype functions inside a separate data container, and
    2. Pass a reference to the data container to all prototype functions as a parameter.

    It's that simple. For example:

    // Helper class to store private data.
    function Data() {};
    
    // Object constructor
    function Point(x, y)
    {
      // container for private vars: all private vars go here
      // we want x, y be changeable via methods only
      var data = new Data;
      data.x = x;
      data.y = y;
    
      ...
    }
    
    // Prototype functions now have access to private instance data
    Point.prototype.getX = function(data)
    {
      return data.x;
    }
    
    Point.prototype.getY = function(data)
    {
      return data.y;
    }
    

    ...

    Read the full story here:

    PPF Design Pattern

提交回复
热议问题