I am not sure what you are trying to achieve, but here's an example where MyClass would be a singleton that has a factory method create that allows creating MyClass instances.
//MyClass will be an object with a create method only
var MyClass = (function() {
function MyClass() {
this.initialized = false;
}
MyClass.prototype = {
init: function () {
this.initialized = true;
return this;
}
};
return {
create: function () {
return new MyClass().init();
}
};
})();
var m = MyClass.create();
console.log(m);
console.log(m.constructor); //Will be Object because we replaced the whole prototype
However, I am not sure why you want to have two constructor functions (init and the constructor itself)? Are you trying to abstract the object creation process away because it is complicated?
I suspect that you simply want to move the constructor logic into another function because of the way you are trying to achieve inheritance.
Are you simply trying to avoid calling the constructor logic when you do the following?
MyChildClass.prototype = new MyParentClass();
If it's the case, using Object.create would fix your problem (it is not supported in old browsers, but there's a shim for it -- the shim support the features you would need, but not everything that Object.create does).
function A(test) {
this.test = test;
}
function B(test) {
A.call(this, test); //call parent constructor
}
B.prototype = Object.create(A.prototype); //inherit from A
var b = new B('test');
console.log(b);
console.log(b instanceof A); //true
You could also use a pure prototypal approach, without using constructor functions together with the new keyword.
var A = {
init: function (test) {
this.test = test;
return this;
}
},
B = Object.create(A),
b;
//override constructor function
B.init = function (test) {
return A.init.call(this, test);
};
b = Object.create(B).init('test');
console.log(b);