【问题标题】:Accessing global variable and asynchronous issue访问全局变量和异步问题
【发布时间】:2013-05-01 15:23:05
【问题描述】:

以下是我刚刚开始编写的一些代码(化身生成器实验)。我希望能够单击一个按钮并更改画布元素的位置,但我遇到了一些问题。

在按钮的点击事件函数中我 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 不是你想象的那样。 console.log(this) 解决之后应该会比较明显。

标签: javascript jquery variables asynchronous global-variables


【解决方案1】:

点击处理程序在不同的上下文中调用,因此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

【讨论】:

  • 在这种情况下,您也可以只使用AvatarGenerator 而不是thisself,但是可以。
  • +1 我建议查看 jQuery 插件模板以了解 base 的传统用法,但在此示例中 self 是相同的,并且可以工作:)
  • 非常感谢!像魅力一样工作。
猜你喜欢
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多