Accessing “Public” methods from “Private” methods in javascript class

后端 未结 4 2097
谎友^
谎友^ 2020-12-31 09:45

Is there a way to call \"public\" javascript functions from \"private\" ones within a class?

Check out the class below:

function Class()
{
    this.p         


        
4条回答
  •  独厮守ぢ
    2020-12-31 10:44

    You can save off a variable in the scope of the constructor to hold a reference to this.

    Please Note: In your example, you left out var before privateMethod = function() making that privateMethod global. I have updated the solution here:

    function Class()
    {
      // store this for later.
      var self = this;
      this.publicMethod = function()
      {
        alert("hello");
      }
    
      var privateMethod = function()
      {
        // call the method on the version we saved in the constructor
        self.publicMethod();
      }
    
      this.test = function()
      {
        privateMethod();
      }
    }
    

提交回复
热议问题