0
我喜歡這本書'有效的JavaScript 68方法來利用.....'。 雖然在這一點上,我覺得它有點超出我的範圍(開始談論畫布和其他人)。 而我從子類構造函數中調用了Item 38:Call Superclass構造函數。雖然在網上獲取圖表並不是該項目的要點(或者可能是),但我很好奇並希望它能夠工作,但有一件事我不明白的是我構建時需要傳遞的'場景'演員。 這個例子是否來自我缺少的其他庫,或者我是否缺少一些代碼來構造「場景」對象...?雖然仔細閱讀「有效的JavaScript」書,不明白項目38(場景)
以下是代碼。
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);
};
會檢查出來。謝謝!! – user3502374