Interpreter bug (JS)

I cant understand the problem here, only can be a interpreter bug.
screemshoot:

here is my code:

// Be the first to 100 gold!
// If you die, you will respawn at 67% gold.
function attackingOrItem(){
var enemy = this.findNearestEnemy();
if (enemy && this.distanceTo(enemy)<10) {
this.shield();
if (this.isReady(“bash”)) {
this.bash(enemy);
}else{
this.attack(enemy);
}
}else{
var item = this.findNearestItem();
if (item) {
this.moveXY(item.pos.x, item.pos.y);
}
}
}

loop {
var flag = this.findFlag();
if (flag) {
if (this.distanceTo(flag)<10) {
this.pickUpFlag(flag);
}else{
var xf = flag.pos.x;
var yf = flag.pos.y;
var x = this.pos.x;
var y = this.pos.y;

		if (xf>x) {
			x=x+10;  
		}else{
			x=x-10;
		}
		if (xy>x) {
			y=y+10;
		}else{
			y=y-10;
		}
		this.moveXY(x, y);
	}
	attackingOrItem();
}else{
attackingOrItem();
}

}

inside of a function the scope of this changes to the function itself in javascript. to get around this you need to define a variable outside of the function and set it to this then access that new variable inside your function instead of this.

var self = this;

function something() {
    var enemy = self.findNearestEnemy();
    self.distanceTo(enemy);
}

1 Like