"Proper"如何继承Javascript中的参考值?

"Proper" way of inheriting reference values in Javascript?

所以,我对 Javascript 很陌生,我正在尝试学习其中的一些 OOP 原则。

我 运行 遇到了问题。所以,我基本上是在为 HTML canvas 创建一个场景图,这意味着我需要一个递归结构。每个节点都必须能够包含一个子节点数组。所以,假设我有一个像这样的基本节点对象:

// Shape class (It is part of the BNBeagle namespace)
Shape: function () {
    this.children = [];
},

没问题。

然后,我继续为一个小示例游戏创建自己的子class,它可能是这样的:

function PlayerShip() {
    // drawShape is a method that's overrided from the Shape class
    this.drawShape = function () {
    BNBeagle.canvasContext.fillStyle = "#FF0000";
    BNBeagle.canvasContext.fillRect(-25, -25, 50, 50);
    };
};

PlayerShip.prototype = new BNBeagle.Shape();

我现在面临的问题是,根据我从研究中收集到的信息,当涉及到数组等引用值时,像这样进行原型继承会产生问题,我很快发现了这一点。基本上,我发现我所有的 PlayerShip 实例都将共享原型中完全相同的 "children" 数组,这显然不好。

根据我在互联网上找到的内容,解决方案似乎是覆盖子 class 中的 属性,基本上是这样做的:

function PlayerShip() {
    this.children = [];

    // drawShape is a method that's overrided from the Shape class
    this.drawShape = function () {
    BNBeagle.canvasContext.fillStyle = "#FF0000";
    BNBeagle.canvasContext.fillRect(-25, -25, 50, 50);
    };
};

只需为 PlayerShip 添加子项 属性。现在,一切都很好,PlayerShip 的所有实例现在都有自己的数组。但是,我只是想知道是否有更多 "user-friendly" 的方法来做到这一点?假设我稍后要发布这个基本框架供 public 使用,人们应该如何确切地知道要覆盖哪些属性才能使对象正常工作?好像有点傻

我想知道是否有一种方法可以做到这一点而不必让 subclassing 覆盖这些类型的参考值? :)

非常感谢!

使用Object.create创建一个原型对象,它不调用构造函数,因此只包含原型:

PlayerShip.prototype = Object.create(BNBeagle.Shape.prototype);

那么就可以在子构造函数的开头调用父构造函数了:

function PlayerShip() {
    // Call parent constructor with appropriate `this`
    BNBeagle.Shape.call(this);

    // drawShape is a method that's overrided from the Shape class
    this.drawShape = function () {
        BNBeagle.canvasContext.fillStyle = "#FF0000";
        BNBeagle.canvasContext.fillRect(-25, -25, 50, 50);
    };
}