JavaScript 类 - 对象初始化时调用方法 [英] JavaScript class - Call method when object initialized
问题描述
我有一个类似于下面的类.创建对象时如何调用我的 init
方法?我不想创建我的对象的实例然后像下面那样调用 initialize .
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 initialize like I do below.
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
};
}
推荐答案
注意.构造函数名称应以大写字母开头,以区别于普通函数,例如MyClass
而不是 myClass
.
NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass
instead of myClass
.
您可以从构造函数中调用 init
:
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
}
或者更简单地说,您可以将 init
函数的主体复制到构造函数的末尾.如果init
函数只被调用一次,则根本不需要它.
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.
这篇关于JavaScript 类 - 对象初始化时调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!