试着给这个加10.y变量,但返回NaN

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

本文关键字:变量 返回 NaN      更新时间:2023-09-26

我似乎做错了什么,找不到任何解决方案。我试图将它们转换成数字并尝试+=,但我得到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);
            }
        });
    };
}

可能是因为它们不是变量吗?

谢谢:)

这是因为keydown回调中的this不是您所期望的。

一种解决方法是将外作用域的this保存到变量中。

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

另一种方法是使用es6 lambas,因为它将绑定作用域。

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

也可以使用bind函数绑定作用域。

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