我不确定您想要实现什么,但是下面是一个例子,其中MyClass
将是一个单例,具有工厂方法create
,允许创建MyClass
实例。
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);
然而,我不确定为什么你想要两个构造函数(init
和 constructor
本身)?你是因为对象创建过程过于复杂而试图将其抽象化吗?
我怀疑你只是想将 constructor
的逻辑移动到另一个函数中,因为你试图实现继承的方式。
你只是想避免在执行以下操作时调用构造函数逻辑吗?
MyChildClass.prototype = new MyParentClass()
如果是这种情况,使用
Object.create
可以解决您的问题(
它不支持旧浏览器,但是有一个类似于“垫片”的东西——它支持您需要的特性,但并不支持 Object.create
的所有功能)。
function A(test) {
this.test = test;
}
function B(test) {
A.call(this, test);
}
B.prototype = Object.create(A.prototype);
var b = new B('test');
console.log(b);
console.log(b instanceof A);
您还可以使用纯原型方法,而不需要与new
关键字一起使用constructor
函数。
var A = {
init: function (test) {
this.test = test;
return this;
}
},
B = Object.create(A),
b;
B.init = function (test) {
return A.init.call(this, test);
};
b = Object.create(B).init('test');
console.log(b);