0

我开始使用 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 元素并且不再指向调用者对象。

4

2 回答 2

0

您可以使用该$.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/

于 2012-07-21T15:52:17.460 回答
0

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

function AClass(){
    this.attribute = /*something*/
    var self = this;

    AClass.prototype.COMPLETE= function() {
        /* Use: self.attributes */
    }

    AClass.prototype.doSomething = function() {
        $("something").animate(..,..,..,COMPLETE);
    }
}
于 2012-07-21T08:04:06.277 回答