Javascript 自动传递父对象
所以我有几节课Javascript 自动传递父对象,javascript,oop,inheritance,Javascript,Oop,Inheritance,所以我有几节课 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.constructo
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;
在我的代码中,每个继承的类都使用call()传递“this”
问题是,如果我有一个包含任何精灵对象的层对象,我希望精灵对象有一个父(超级)引用,但我不能这样做,因为类构造函数使用它来设置属性
那么,有人知道我如何传递父级,或者(我知道这听起来很愚蠢,已经很晚了)能够在类构造函数中获得父级作用域吗
在写这篇文章的时候,我意识到这可能和在对象被设置为子对象之后设置父属性一样简单,但我正在寻找确认,这是否是最好的方法,或者是否有人知道更好的方法。另外,请随时告诉我,我对原型一无所知,因为我还在学习它。:-)
-谢谢这行吗?它不是自动的,但仍然有效。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的父变量
此外,如果您正在寻找继承,请尝试使用coffee脚本。它可以编译回javascript并为您处理大多数继承问题。我真的不理解这个问题。请澄清“我希望精灵对象有一个父(超级)引用,但我不能这样做,因为类构造函数使用它来设置属性。”。请注意,您的一些呼叫是错误的。例如,
ImageClass.call(img,w,h,x,y)代码>应该是ImageClass.call(this,img,w,h,x,y)代码>。我从头开始将基本结构重写为stackoverflow,因此可能有一两处出错。我主要需要能够访问层对象父对象的维度,例如,能够相对地调整子对象的大小和位置。我仍然不明白为什么不能将层作为参数传递给sprite
,或者在sprite.prototype
上创建允许设置父对象的方法。是的,我推测这将是一个解决方案。至少有人帮我证实了这一点,谢谢。“另外,如果你想继承,试试咖啡脚本。”呃,如果你打算使用预处理器,那就使用下一个JS版本,它引入了类:。我知道,我对此很兴奋,但直到夏天才开始,即使到那时,我也怀疑只支持FF和Chrome