访问全局变量和异步问题

Accessing global variable and asynchronous issue

本文关键字:问题 异步 全局变量 访问      更新时间:2023-09-26

下面是一些我刚刚开始工作的代码(一个角色生成器实验)。我想能够点击一个按钮,并改变画布元素的位置,但我遇到了一些问题。

在点击事件功能上的按钮我console.log out canvasTop…

console.log(this.canvasTop);

…然而,它是没有定义的。我可以在代码的其他任何地方访问变量,除了在这个点击事件函数中。为什么会这样?

另一件事是接下来的两行…

this.canvasTop += 10;
AvatarGenerator.canvas();

…在第一行中,我想迭代canvasTop值,在第二行中调用绘制画布的函数。然而,似乎第二行在第一行之前运行(是的,JS是异步的,我知道),这意味着画布元素不会移动,直到下次我点击按钮。我怎么解决这个问题?

提前感谢!

代码:

AvatarGenerator = {
    canvasTop: 50,
    canvasLeft: 50, 
    canvas: $('#canvas')[0],
    context: canvas.getContext('2d'),
    init: function() {
        AvatarGenerator.canvas();
        AvatarGenerator.toolBox();
    },
    canvas: function() {
        console.log(this.canvasTop); // <-- 50
        this.context.beginPath();
        this.context.moveTo(this.canvasLeft, this.canvasTop);
        this.context.lineTo(300, 300);
        this.context.stroke();
    },
    toolBox: function() {
        var moveLeftBtn = $('#moveLeftBtn');
        moveLeftBtn.on('click', function(){
            console.log(this.canvasTop); // <-- undefined, why?
            this.canvasTop += 10;
            AvatarGenerator.canvas();
        });
    }
};

单击处理程序在不同的上下文中被调用,因此this不再指向您的对象。

试试这个:

var self = this;
moveLeftBtn.on('click', function(){
  console.log(self.canvasTop);
  self.canvasTop += 10;
  AvatarGenerator.canvas();
});

或者,对于现代浏览器,你可以将你的对象绑定到你的函数,这样你就不需要self:

moveLeftBtn.on('click', function(){
  console.log(this.canvasTop);
  this.canvasTop += 10;
  AvatarGenerator.canvas();
}.bind(this));
//^^^^^^^^^^ this determines what 'this' in the callback function is pointing to