这可能是不可能的,但我很好奇.是否可以使用公共工厂方法定义私有构造函数?
function MyParentClass() {}
MyParentClass.prototype.init = function() { ... }
function MyChildClass() {}
MyChildClass.prototype = new MyParentClass();
MyChildClass.prototype.init = function() {
...
MyParentClass.prototype.init.apply(this);
...
}
MyChildClass.Create = function() {
var instance = new MyChildClass();
instance.init();
return instance;
}
Run Code Online (Sandbox Code Playgroud)
是否可以隐藏2个构造函数并仅显示Create()?
这种可覆盖的init()方法的其他方法也是受欢迎的.谢谢.
我不确定你想要实现什么,但这里有一个例子,它MyClass是一个单例,它有一个create允许创建MyClass实例的工厂方法.
//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
Run Code Online (Sandbox Code Playgroud)
但是,我不确定为什么你想要两个构造函数(init和它constructor自己)?您是否试图将对象创建过程抽象出来,因为它很复杂?
我怀疑你只是想将constructor逻辑移动到另一个函数中,因为你试图实现继承.
您是否只是在尝试避免在执行以下操作时调用构造函数逻辑?
MyChildClass.prototype = new MyParentClass();
Run Code Online (Sandbox Code Playgroud)
如果是这种情况,使用Object.create将解决您的问题(在旧浏览器中不支持它,但它有一个垫片 - 垫片支持您需要的功能,但不是所有Object.create功能).
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
Run Code Online (Sandbox Code Playgroud)
您也可以使用纯原型方法,而不必将constructor函数与new关键字一起使用.
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);
Run Code Online (Sandbox Code Playgroud)