如果在 JavaScript 中子类化一个“类”是这样完成的:
var ParentClass = function() {
// something
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
...父类有必填参数怎么办?
var ParentClass = function(requiredParameter) {
if (typeof requiredParameter === 'undefined') {
throw new TypeError("'requiredParameter' is required!");
}
};
var ChildClass = function() {
// something
};
ChildClass.prototype = new ParentClass();
// ^ Throws TypeError
Thanks.
这是它的完成方式:
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;
现场演示: http://jsfiddle.net/ECCgt/ http://jsfiddle.net/ECCgt/(在控制台分析实例)
你这样做的方式
ChildClass.prototype = new ParentClass();
是一个肮脏的黑客行为,已经被破坏,应该避免。使用Object.create
建立两个原型对象之间的继承关系。
第二行
Child.prototype.constructor = Child;
有点可选。我们正在纠正constructor
属性,因为我们必须覆盖Child.prototype
以便设立继承权。如果你不关心constructor
属性,只需省略该行即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)