【发布时间】:2016-07-09 12:58:10
【问题描述】:
此代码引发错误 - “无法读取未定义的属性 'x'”。 我想分配这个函数,然后用一个参数调用它(函数“crash”回答关于与其他对象碰撞的问题)。
function Obj(x, y, height, width, type) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
if(type == "obstacle") {
this.speedX = levelManager.level;
}
var self = this;
this.isNotUsed = function() {
return self.x < 0;
};
this.drawSelf = function(img) {
ctx.drawImage(img, self.x, self.y, self.width, self.height);
};
if(type == "hero"){
this.crash = function(otherObj) {
var myLeft = this.x;
var myRight = this.x + this.width;
var myBottom = this.y + this.height;
var otherLeft = (otherObj.x) || 0; //error occurs here
var otherRight = (otherObj.x + otherObj.width) || 0;
var otherTop = otherObj.y || 0;
var collision = true;
if((myBottom < otherTop) ||
(myRight < otherLeft) ||
(myLeft > otherRight)) {collision = false;}
return collision;
};
}
}
var hero = new Obj(0, 0, 40, 40, "hero");
【问题讨论】:
-
如何调用
crash()函数? -
你的意思是
crash函数在调用自己吗? -
@gurvinder372 这也是我不明白的......
-
你没有定义
otherObj -
@daniel432 没办法,您发布的代码有效(请参阅我的回答中的 sn-p)。您在其他地方还有其他代码,请发布完整示例。
标签: javascript class oop object