自动传递父对象

passing parent object automatically

所以我有几个 classes

function BaseClass(x, y){
    this.x = x;
    this.y = y;
}

function ImageClass(img, w, h, x, y){
    BaseClass.call(this, x, y);
    this.img = img;
}
ImageClass.prototype = Object.create(BaseClass.protoype);
ImageClass.prototype.constructor = ImageClass;

function LayerClass(img, w, h, x, y){
    ImageClass.call(img, w, h, x, y);
    this.collection = [];
    this.createSprite = function(img, r, a, w, h, x, y){
        this.collection.push(new Sprite(img, r, a, w, h, x, y));
    }
}
LayerClass.prototype = Object.create(ImageClass.prototype);
LayerClass.prototype.constructor = LayerClass;

function SpriteClass(img, r, a, w, h, x, y){
    ImageClass.call(img, w, h, x, y);
    this.r = r;
    this.a = a;
}
SpriteClass.prototype = Object.create(ImageClass.prototype);
SpriteClass.prototype.constructor = SpriteClass;

在我的代码中,每个继承的 classes 都使用 call() 来传递 'this'

问题是,如果我有一个包含任何 Sprite 对象的 Layer 对象,我希望 Sprite 对象有一个父(超级)引用,但我不能这样做,因为 class构造函数使用它来设置属性。

所以有人知道我如何传递父级或者(我知道这听起来很愚蠢,已经晚了)能够在 class 构造函数中获得父级作用域吗?

在写这篇文章时,我意识到它可能就像在将对象设置为子对象后设置父对象 属性 一样简单,但我正在寻找确认这是否是最好的方法或者是否有人知道一些事情更好的。也可以随时告诉我我对原型一无所知,因为我还在学习它。 :-)

-谢谢

这行得通吗?它不是自动的,但仍然有效。 Javascript 没有对 类 的原生支持,因此它有其局限性。

function LayerClass(img, w, h, x, y){
    ImageClass.call(img, w, h, x, y);
    this.collection = [];
    this.createSprite = function(img, r, a, w, h, x, y){
        var spriteObj = new Sprite(img, r, a, w, h, x, y);
        spriteObj.parent = this;
        this.collection.push(spriteObj);
    }
}

您将能够访问 spriteObject 的父变量。

此外,如果您正在寻找继承,请尝试咖啡脚本。它编译回 javascript 并为您处理大部分继承问题。