在JavaScript中对具有必需参数的类进行子类化

Jon*_*han 12 javascript oop

如果在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物业,请忽略该行.

  • 我想我们有不同的"相当新"的想法;) (2认同)
  • @ user886931无论如何它都无关紧要.有ES5垫片,所以你可以安全地使用`Object.create`.案件结案. (2认同)

Dag*_*bit 4

像这样子类化它:

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)

现在你不必担心它,因为你不必调用父构造函数来子类化它:)

  • Šime:http://jsfiddle.net/RsgJf/ ... Trevor,我同意将所有这些封装到某种“继承”函数中更干净。我只是想让事情尽可能接近原始示例。 (2认同)