JavaScript class - Call method when object initialized

前端 未结 5 1311
时光取名叫无心
时光取名叫无心 2021-02-02 09:56

I have a class similar to the one below. How do I call my init method when the object is created? I don\'t want to have to create an instance of my object then call

5条回答
  •  一个人的身影
    2021-02-02 10:42

    See below for one possible answer, and some corrections to your code.

    function myClass(v1, v2) 
    {
        // public vars
        this.var1 = v1;
    
        // private vars
        // use var to actually make this private
        var var2 = v2;
    
        // pub methods
        this.init = function() {
            // do some stuff        
        };
    
        // private methods
        // this will be private as though it had been declared with var
        function someMethod() {
            // do some private stuff
        };
    
        //call init
        this.init();
    }
    

提交回复
热议问题