如果在JavaScript中继承"class"是这样的:
var ParentClass = function() {
// something
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
Run Code Online (Sandbox Code Playgroud)
...当父类需要参数时,我该怎么办?
var ParentClass = function(requiredParameter) {
if (typeof requiredParameter === 'undefined') {
throw new TypeError("'requiredParameter' is required!");
}
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
// ^ Throws TypeError
Run Code Online (Sandbox Code Playgroud)
谢谢.
Šim*_*das 26
这就是它的完成方式:
function Parent( a ) {
this.a = a;
}
function Child( a, b ) {
Parent.call( this, a ); // this is crucial
this.b = b;
}
Child.prototype = Object.create( Parent.prototype );
Child.prototype.constructor = Child;
Run Code Online (Sandbox Code Playgroud)
现场演示: http ://jsfiddle.net/ECCgt/(分析控制台中的实例)
你这样做的方式
ChildClass.prototype = new ParentClass();
Run Code Online (Sandbox Code Playgroud)
是一个破坏的肮脏的黑客,应该避免.使用Object.create设立两个原型对象之间的继承关系.
第二行
Child.prototype.constructor = Child;
Run Code Online (Sandbox Code Playgroud)
有点可选.我们正在更正constructor属性,因为我们必须覆盖Child.prototype才能设置继承.如果您不关心该constructor物业,请忽略该行.
像这样子类化它:
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
Run Code Online (Sandbox Code Playgroud)
现在你不必担心它,因为你不必调用父构造函数来子类化它:)