我正在为学校构建一个jquery游戏的过程中,我试图让方法通过在setTimeout()的末尾运行来调用create()函数 (我正在使用setTimeout,因为addEnemySpeed是一个随机生成的,所以它每次都会改变),但它不工作该方法只从被调用启动(smallEnemy.create())运行一次,但永远不会回忆自己?我希望这只是我的一个简单的疏忽?先谢谢您的帮助。 CHEERS。jQuery对象构造函数 - 方法调用本身
// OBSTACLE OBJECT CONSTRUCTOR //
function Obstacle(type, className, speed, startHealth, currentHealth, damageCause) {
this.type = type;
this.className = className;
this.speed = speed;
this.endX = -160;
this.startHealth = startHealth;
this.currentHealth = currentHealth;
this.damageCause = damageCause;
this.create = function(type, endX, speed) {
type = this.type;
endX = this.endX;
speed = this.speed;
var $obstacle = $('<div>');
// if the obstacle is a enemy add enemies class
if (type == 'smallEnemy' || type == 'bigEnemy') {
$obstacle.addClass('enemies');
}
// add correct class name
$obstacle.addClass(type);
// add obstacle to playground
$('#playGround').append($obstacle);
// animate obstacle down x axis remove if hits destination
$obstacle.transition({
x: endX
}, speed, 'linear', function() {
$(this).remove();
});
setTimeout(this.create,addEnemySpeed);
};
}
smallEnemy.create()
有多少次你想'this.create'要重复? –
对于初学者来说,当''this.create'被'setTimeout()'调用时'this'的值不正确。你可以使用'setTimeout(this.create.bind(this)',addEnemySpeed)来代替。 – jfriend00
@AminJafari我需要它继续不断地调用自己,直到我不再需要它。游戏运行在一个定时器上,如果其他语句运行,如果语句控制它,则例如:如果定时器在100和80之间,我将以随机速度创建一种类型的障碍,如果定时器在80和60之间将创建另一种障碍等等 感谢您的帮助 – VinceBrown