构造函数中的函数以某种方式调用自身
Function in a constructor invokes itself somehow
此代码抛出错误 - "无法读取未定义的属性'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");
代码运行良好(见片段)。如果您调用hero.crash()
而不带任何参数,则可能出现的唯一错误。为了避免这种情况,您可以更改 crash() 函数添加为函数的第一行 otherObject = otherObject || {};
。或者更好的是,正如注释中所建议的,如果 otherObject 未定义,只需返回:
if (!otherObject) return false;
或者如果它不是对象
if (typeof otherObject !== 'object') return false;
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");
console.log('THIS IS PRINTED')
console.log(hero.crash('{}'));
console.log('BUT FROM HERE NO MORE');
console.log(hero.crash());
相关文章:
- 以不同的方式调用javascript函数
- 以编程方式调用javascript函数
- 以 func(a)(b)(c) 的方式调用的 Javascript 函数
- 如何用两种不同的方式调用同一个函数
- 以编程方式调用模糊会禁用与浏览器窗口的交互
- 以编程方式调用选项卡捕获引发异常
- 防止以编程方式调用 django-rest-framework API
- 如何在回发上保留选定的选项卡或以编程方式调用之前激活方法
- jwysiwyg以编程方式调用工具栏单击
- Dropzone.js以编程方式调用accept()函数
- 如何通过JQuery或Javascript以编程方式调用服务器单击
- 如何在 d3 中以编程方式调用“单击”事件
- 如何以编程方式调用;点击“;的css
- 使用JQuery以不可见的方式调用URL并返回成功/错误标志
- javascript onclick事件在internet explorer中以编程方式调用时未冒泡<=8.
- 以全局函数的方式调用局部函数
- 可以以编程方式调用事件处理程序吗?
- 是否可以在JS中以编程方式调用电话号码?
- 如何在angularjs中以编程方式调用自定义指令
- 以编程方式调用onclick和onchange不能按预期工作