javascript - 如何创建与其他对象类型相同的新对象

标签 javascript inheritance

假设您在 javascript 中有一个对象层次结构,其中“A”是父类(super class),“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;

最佳答案

如果你仔细restore constructors (就像你已经在你的例子中所做的那样)你可以调用'new 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

关于javascript - 如何创建与其他对象类型相同的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642534/

相关文章:

javascript - 通过 css/javascript 更改指定样式?

javascript - 如何在 PHP 服务器端处理具有多个文件的 JavaScript 表单数据?

Java 扩展 ArrayList<Dummy> 函数

c# - 继承和共享静态字段

javascript - 有没有办法让页面主体像在 WordPress 网站上那样在页面顶部的图像上滑动?

javascript - 将复选框与另一个输入相关联

java - 当返回类型为 List 时,无法覆盖父类(super class)中的方法

java - 使用类层次结构中的某些子类

c++ - 在给定指向父类(super class)的指针的子类上调用方法

javascript - 修改 Controller 属性时,Ember 不更新模板