JQuery动画完整功能:如何恢复我的"老这个”;

JQuery Animation Complete Function: How to recover my "old this"?

本文关键字:quot 我的 恢复 动画 功能 何恢复 JQuery      更新时间:2023-12-12

我刚开始使用jQuery,遇到了以下问题:

function AClass(){
    this.attribute = /*something*/
}
AClass.prototype.COMPLETE= function() {
    /*FROM HERE I WANT TO ACCESS TO THE ABOVE "this.attribute"!!*/
}
AClass.prototype.doSomething = function() {
    $("something").animate(..,..,.., this.COMPLETE);
}

所以,这就是我面临的问题。通过完整动画函数,我想访问AClass的属性值。问题是,在该上下文中,this指向正在设置动画的DOM元素,而不再指向调用方对象。

您可以使用$.proxy()方法将特定上下文绑定到回调。或者,如果你不关心旧的浏览器(即IE<9),你可以使用(JS 1.8.5).bind()方法。基本上,在需要提供yourFunction作为回调的地方放置:

$.proxy(yourFunction, theRequiredContext)
// or
yourFunction.bind(theRequiredContext)

在示例代码的上下文中:

function AClass(){
    this.attribute = /*something*/
}
AClass.prototype.COMPLETE= function() {
    /*FROM HERE I WANT TO ACCESS TO THE ABOVE "this.attribute"!!*/
}
AClass.prototype.doSomething = function() {
    $("something").animate(..,..,..,$.proxy(this.COMPLETE, this));
}

演示:http://jsfiddle.net/P9mbG/

将对原始this的引用保存在变量中:

function AClass(){
    this.attribute = /*something*/
    var self = this;
    AClass.prototype.COMPLETE= function() {
        /* Use: self.attributes */
    }
    AClass.prototype.doSomething = function() {
        $("something").animate(..,..,..,COMPLETE);
    }
}