![](/img/trans.png)
[英]Uncaught TypeError: Cannot read property of undefined - javascript
[英]Uncaught TypeError: Cannot read property 'canvas' of undefined - Javascript Object
我對如何使用,定義,更改和取消設置javascript對象感到困惑。
我的JavaScript對象是:
var Ship = function(){
return {
canvas: $('#area')[0],
canvas_width: this.canvas.width,
canvas_height: this.canvas.height,
context: this.canvas.getContext("2d"),
ship_image: new Image(),
ship_width: null,
ship_height: null,
ship_x: 0,
ship_y: 0,
init: function() {
this.ship_image.onload = function() {
this.ship_width = this.width;
this.ship_height = this.height;
this.ship_x = (this.canvas_width / 2) - (this.ship_width / 2);
this.ship_y = this.canvas_height - this.height;
this.draw(
this.ship_x,
this.ship_y
);
}
this.ship_image.src = "ship.gif";
},
draw: function(x, y) {
this.context.drawImage(
this.ship_image,
x,
y
);
}
}
}();
當我執行這段代碼時;
$(function(){
Ship.init();
Controller.init();
});
我每次都會收到此錯誤。
Uncaught TypeError:無法讀取第4行(ship.js)上未定義的屬性'width'
未捕獲到的TypeError:第29行上的Ship不是函數(index.html / Ship.init())
我現在應該怎么辦?
問題是this.canvas
沒有指向對象ship
的canvas
屬性,而是指向全局對象window
。 您需要不同地初始化canvas_width
,例如在init函數中。 和context
相同:
var Ship = function () {
return {
canvas: $('#area')[0],
ship_image: new Image(),
ship_width: null,
ship_height: null,
ship_x: 0,
ship_y: 0,
init: function () {
this.context = this.canvas.getContext("2d");
this.canvas_width = this.canvas.width;
this.canvas_height = this.canvas.height;
this.ship_image.onload = function () {
this.ship_width = this.ship_image.width;
this.ship_height = this.ship_image.height;
this.ship_x = (this.canvas_width / 2) - (this.ship_width / 2);
this.ship_y = this.canvas_height - this.ship_image.height;
this.draw(this.ship_x, this.ship_y);
}.bind(this);
this.ship_image.src = "ship.gif";
},
draw: function (x, y) {
this.context.drawImage(this.ship_image, x, y);
}
}
}();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.