如何在jQuery回调函数中访问属性?

Dra*_*ex_ 2 javascript oop jquery class object

var some_name =
{
    moving:false,

    show : function ()
    {
        this.moving = true;

        $('element').slideDown(5000, function ()
        {
            this.moving = false; //How to access to attribute "moving" of class some_name?
        });
    },
}
Run Code Online (Sandbox Code Playgroud)

代码中的问题.

Arn*_*anc 6

您可以将回调函数绑定到当前上下文:

$('element').slideDown(5000, $.proxy(function() {
    this.moving = false;
}), this); // "this" inside of the function will be this "this"
Run Code Online (Sandbox Code Playgroud)

看到 jQuery.proxy


或者你可以这样做:

this是当前上下文,它的值取决于函数的调用方式.您可以this在函数外部分配变量,并使用此变量:

var that = this;
$('element').slideDown(5000, function() {
    that.moving = false; //use that instead of this here
});
Run Code Online (Sandbox Code Playgroud)