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

后端 未结 4 2113
谎友^
谎友^ 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:42

    torazaburo's answer is the best one, as it avoids creation of multiple copies of the private members. I'm surprised that Crockford doesn't mention it at all. Alternately, depending on the syntax you prefer for declaring public member functions, you could do this:

    function Class()
    {}
    
    (function() {
        var privateMethod = function(self) {
            self.publicMethod();
        };
    
        Class.prototype.publicMethod = function() {
            alert('hello');
        };
    
        Class.prototype.test = function() {
            privateMethod(this);
        };
    }());
    

提交回复
热议问题