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

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

    The accepted answer has the possibly undesirable side effect that separate copies of publicMethod, test, and privateMethod will be created in each instance. The idiom for avoiding this is:

    function Class()
    {}
    
    Class.prototype=(function()
    {
        var privateMethod = function(self)
        {
            self.publicMethod();
        }
    
    
        return 
        {
            publicMethod: function()
            {
                alert("hello");
            },
            test: function()
            {
                privateMethod(this);
            }
        };
    }());
    

    In other words, you need to pass the this to the private function as an argument. In return, you get a true prototype without having to pollute each instance with its own versions of the private and public functions.

提交回复
热议问题