gpt4 book ai didi

javascript - 构造函数中的函数以某种方式调用自身

转载 作者:行者123 更新时间:2023-12-03 06:34:41 25 4
gpt4 key购买 nike

此代码抛出错误 - “无法读取未定义的属性 '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 - 构造函数中的函数以某种方式调用自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38282057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com