Myhre Myhre - 1 month ago 5
HTML Question

Trying to add 10 to this.y variable, but returns NaN

I seem to have done something wrong and cant find any solutions. I've tried to convert them into numbers and tried += but i get NaN.

function circle() {
this.x = 60;
this.y = 200;
this.draw = function() {
ellipse(this.x, this.y, 20, "green");
};


this.move = function() {
$(document).keydown(function(e) {
// console.log(e.keyCode);
if (e.keyCode === 68) {
this.y += 1;
console.log(this.y);
}
});
};

}


Might it be because they are not variables?

thanks :)

Answer

This is because this inside keydown callback is not what your expecting.

One way to solve is to save this of outer scope to variable.

var me = this;
me.x = 60;
me.y = 200;
....

me.y += 1; //use me istead of this.
console.log(me.y);

Other way could be to use es6 lambas, bacause it would bind scope right.

$(document).keydown(e => {//lamba instead of function
    if (e.keyCode === 68) {
        this.y += 1;
        console.log(this.y);
    }
});

You can also use bind function to bind scope.

$(document).keydown((function(e) {//lamba instead of function
    if (e.keyCode === 68) {
        this.y += 1;
        console.log(this.y);
    }
}).bind(this));
Comments