JavaScript class - Call method when object initialized

前端 未结 5 1295
时光取名叫无心
时光取名叫无心 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:46

    NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

    Either you can call init from your constructor function:

    var myObj = new MyClass(2, true);
    
    function MyClass(v1, v2) 
    {
        // ...
    
        // pub methods
        this.init = function() {
            // do some stuff        
        };
    
        // ...
    
        this.init(); // <------------ added this
    }
    

    Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

提交回复
热议问题