在JavaScript中对具有必需参数的类进行子类化 [英] Subclassing a class with required parameters in JavaScript
本文介绍了在JavaScript中对具有必需参数的类进行子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果在JavaScript中对class进行子类化是这样完成的:
If subclassing a "class" in JavaScript is done like so:
var ParentClass = function() {
// something
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
...如果父类需要参数,我该怎么办?
... what should I do when the parent class has required parameters?
var ParentClass = function(requiredParameter) {
if (typeof requiredParameter === 'undefined') {
throw new TypeError("'requiredParameter' is required!");
}
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
// ^ Throws TypeError
谢谢。
推荐答案
将它改为类似:
function clone (obj) {
if (!obj) return;
clone.prototype = obj;
return new clone();
}
var ParentClass = function() {
// something
};
var ChildClass = function() {
// something
};
ChildClass.prototype = clone(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass; // if you want
现在你不必担心它,因为你没有必须调用父构造函数将其子类化:)
Now you don't have to worry about it, because you don't have to call the parent constructor to subclass it :)
这篇关于在JavaScript中对具有必需参数的类进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文