Constructor or init function for an object
Updated for 2020
While at the time of answering this questions classes were not widely available in JavaScript, this is no longer the case. Most major browsers now support the ES2015 class syntax, and with the prevalence of JavaScript transpilers providing backwards compatibility for those environments which don't support it, classes are now fairly safe to use and will look more natural to those coming to JavaScript from common OOP languages.
ES2015 Class version
class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
}
init () {
// Initialization code here.
}
}
let currentAbc = new Abc(obj, obj);
The private version is much the same as it was previously, since visibility keywords are not provided in the new class syntax
class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init = function () {
// Initialization code here.
}
this.init();
}
}
let currentAbc = new Abc(obj, obj);
There is also the option of creating the class in closure, which is what I believe some compilers may do to ensure that the function is private at runtime.
const Abc = (function() {
function privateInit () {
// Do initialization here
}
return class Abc {
constructor (aProperty, bProperty) {
this.aProperty = aProperty;
this.bProperty = bProperty;
privateInit.call(this);
}
};
})();
const currentAbc = new Abc(obj, obj);
If you're using a superset such as TypeScript, you can simply implement the init
function privately, although this is only a compiler check, so it protects you from yourself, but not from external code.
class Abc {
aProperty: any;
bProperty: any;
constructor (aProperty: any, bProperty: any) {
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
}
private init () {
// Initialization code here.
}
}
let currentAbc = new Abc(obj, obj);
Original Answer
Perhaps something like this?
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init = function(){
// Do things here.
}
this.init();
};
var currentAbc = new Abc(obj,obj);
You can just call init()
from the constructor function
var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
this.init();
};
Here is a fiddle demonstrating: http://jsfiddle.net/CHvFk/