javascript - JS : create a subclass instance from a superclass instance

标签 javascript oop inheritance

我知道如何从父类(super class)原型(prototype)创建子类原型(prototype)。但是,如果我已经有了父类(super class)对象的实例来创建子类对象怎么办?

在 JS 中使用经典 OOP 的 MDN 示例:

// Shape - superclass
function Shape(x, y) {
    this.x = x;
    this.y = y;
}
// Rectangle - subclass
function Rectangle(x, y, w, h) {
    Shape.call(this, x, y); // call super constructor.
    this.w = w;
    this.h = h;
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

如果我已经有一个形状的实例并且我想基于它创建一个矩形怎么办?

function createSquareFromShape(shape) {
    var rect = new Rectangle(1, 1);
    rect = Object.create(shape);
    // rect gets the shape prototype but loses Rectangle
}

我知道我可以手动将属性从一个对象复制到另一个对象,但也许有更快更简单的方法?

最佳答案

Object.create 返回一个新对象,其原型(prototype)设置为您作为第一个参数传递给 create 方法的任何对象。因此,您正在用一个新对象覆盖您的 rect 变量。

您将无法从 Shape 对象创建 Rectangle 对象,因为 Rectangle 是 Shape 对象的特化,Shape 不知道它以何种方式被特化。

如果您决心学习基于类的 JavaScript 样式,我会建议您在 Shape“类”(对象)上使用一个函数,该函数可以从中自行创建矩形。或者一个可以获取一个 Shape 并返回一个 Rectangle 的工厂,按照

var ShapeFactory = {
    CreateRectange: function(shape, w, h) {
        var rect = new Rectangle();
        rect.x = shape.x;
        rect.y = shape.y;
        rect.w = w;
        rect.h = h;
        return rect;
    }
}

var shape = new Shape(1,1);
var rect = ShapeFactory.CreateRectangle(shape, 1, 1);

感觉有必要推荐一下这本书系列https://github.com/getify/You-Dont-Know-JS具体https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes并自己决定是否值得学习基于类的模式(这可能是社区中一个非常两极分化的话题)

关于javascript - JS : create a subclass instance from a superclass instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40043731/

相关文章:

javascript - 可观察的添加延迟 - Angular 2

vb.net - 在 Vb.net 中将字符串转换为自定义类类型

java - 避免显式强制转换的最佳方法

javascript - 在页面内包含 API 调用以延迟加载

Javascript - 如何找到变量的名称而不是它所保存的值

javascript - extjs 在 chrome 中工作正常,但在 firefox 或 ie 中不显示任何内容

php - 如何实现这个: object->object->property

java - God Class code smell中是否考虑了私有(private)方法?

java - 更改按钮数组中按钮的颜色并将其他按钮恢复为默认值

java - 使用抽象类创建对象