JavaScript类 - 初始化对象时的调用方法

Rya*_*son 21 javascript object

我有一个类似于下面的类.如何init在创建对象时调用我的方法?我不想创建我的对象的实例然后像我下面那样调用initialize.

var myObj = new myClass(2, true);
myObj.init();

function myClass(v1, v2) 
{
    // public vars
    this.var1 = v1;

    // private vars
    var2 = v2;

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // private methods
    someMethod = function() {
        // do some private stuff
    };
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 32

NB.构造函数名称应以大写字母开头,以区别于普通函数,例如,MyClass而不是myClass.

您可以init从构造函数调用:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}
Run Code Online (Sandbox Code Playgroud)

或者更简单地说,您可以将init函数体复制到构造函数的末尾.init如果仅调用一次,则根本不需要实际具有功能.


Kun*_*nok 9

有更平滑的方法来做到这一点:

this.init = function(){
  // method body
}();
Run Code Online (Sandbox Code Playgroud)

这将创建方法并调用它.