2
假设您在JavaScript中具有对象层次结构,其中“A”是超类,并且“B”和“C”都从它继承。 “A”中有一些方法想要创建并返回实际上是任何类型对象的新实例。因此,如果在类型为“B”的对象上调用对象“A”中的这些方法之一,则应该创建类型为“B”的新对象并将其返回,但显然对象“A”不知道任何关于“B”(而不应该)。如何创建与某些其他对象相同类型的新对象
那么,如何创建与某个其他对象类型相同的对象,而不管它是什么类型(如invert
方法所示)?
代码示例:
function A() {
// constructor logic here
}
A.prototype = {
invert: function() {
// question: how do I create an object here that is the same
// type as whatever this object is (could be A, B or C)
}
};
// -------------------------
// B - subclass of A
function B() {
// call A superclass constructor
A.apply(this, arguments);
}
B.prototype = new A();
B.prototype.constructor = B;
// methods of B
B.prototype.negate = function() {
// method of subclass
}
// -------------------------
// C - subclass of A
function C() {
// call A superclass constructor
A.apply(this, arguments);
}
C.prototype = new A();
C.prototype.constructor = C;