我喜欢这本书'有效的Javascript 68方法来驾驭.....'。 虽然在这一点上,我觉得它有点超出我的范围(开始谈论画布和其他)。 我遇到了第38项:从子类构造函数调用超类构造函数。虽然在网上获取图形不是项目的重点(或者可能是这样),但我很好奇并希望它能够工作,但有一件事我不明白是我在构建时需要传递的“场景”演员。 这是我失踪的其他库中的示例,还是我错过了构建'scene'对象的一些代码...?
以下是代码。
function Scene(context, width, height, images) {
this.context = context;
this.width = width;
this.height = height;
this.images = images;
this.actors = [];
}
Scene.prototype.register = function(actor) {
this.actors.push(actor);
};
Scene.prototype.unregister = function(actor) {
var i = this.actors.indexOf(actor);
if ( i >= 0 ) {
this.actors.splice(i,1);
}
};
Scene.prototype,draw = function() {
this.context.clearRect(0,0, this.width, this.height);
for (var a = this.actors, i = 0, n = a.length; i < n; i++) {
a[i].draw();
}
};
function Actor(scene,x,y) {
this.scene = scene;
this.x = x;
this.y = y;
scene.register(this);
}
Actor.prototype.moveTo = function(x,y) {
this.x = x;
this.y = y;
this.scene.draw();
};
Actor.prototype.exit = function() {
this.scene.unregister(this);
this.scene.draw();
};
Actor.prototype.draw = function() {
var image = this.scene.images[this.type];
this.scene.context.drawImage(image, this.x, this.y);
};
Actor.prototype.width = function() {
return this.scene.images[this.type].width;
};
Actor.prototype.height = function() {
return this.scene.images[this.type].height;
};
function SpaceShip(scene,x,y) {
Actor.call(this.scene,x,y);
this.points = 0;
}
SpaceShip.prototype = Object.create(Actor.prototype);
SpaceShip.prototype = new Actor('jot', 3,2);
SpaceShip.prototype.type = "spaceShip";
SpaceShip.prototype.scorePoint = function() {
this.points++;
};
SpaceShip.prototype.left = function() {
thils.moveTo(Math.max(this.x - 10, 0 ), this.y);
};
SpaceShip.prototype.right = function() {
var maxWidth = this.scene.width - this.width();
this.moveTo(Math.min(this.x + 10, maxWidth), this.y);
};
答案 0 :(得分:0)
scene
函数中的Actor
参数显然是指Scene
的实例。此示例与名为Mediator Pattern
的模式有一些相似之处,如下所述:http://www.dofactory.com/javascript/mediator-design-pattern
顺便说一句,你的代码存在一些缺陷:
//the first argument of the `call` function is the scope, in this case `this` which refers to the newly created SpaceShip instance
function SpaceShip(scene,x,y) {
Actor.call(this,scene,x,y);
this.points = 0;
}
SpaceShip.prototype = Object.create(Actor.prototype);
//you do not need this line
//SpaceShip.prototype = new Actor('jot', 3,2);
//but you could add this line to set the constructor property to SpaceShip
SpaceShip.prototype.constructor = SpaceShip;