2014-02-08 105 views
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; 

回答

1

如果你仔细restore constructors(就像你在你的例子已经这样做),你可以叫 '新this.constructor()':

function A() { 
    this.label = 'A'; 
} 

A.prototype = { 
    constructor: A, 
    quux: function() { 
    return new this.constructor(/*ctor args here*/); 
    } 
}; 

function B() { 
    this.label = 'B'; 
} 

B.prototype = new A(); 
B.prototype.constructor = B; 

function C() { 
    this.label = 'C'; 
} 

C.prototype = new A(); 
C.prototype.constructor = C; 

console.log(new A().quux().label); // prints A 
console.log(new B().quux().label); // prints B 
console.log(new C().quux().label); // prints C 
相关问题