对象回调函数是未定义的Javascript

时间:2014-12-22 12:15:55

标签: javascript jquery object

我有以下object

function AnimatedObject(object)
{
    this.object = object;
    /*
        Functions
     */
    this.fadeOutAnimation = fadeOutAnimation;
    this.objectToggle = objectToggle;
    this.objectClick = objectClick;
}
function fadeOutAnimation()
{
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        this.objectToggle();
    });

}

function objectToggle()
{
    this.object.toggle();
}

animate函数中我称为this.objectToggle();

然而,当它完成动画时,我得到undefined is not a function

我非常认可,因为内部回调函数没有引用object

我的问题是如何为它提供对象的引用,从而允许我从回调函数内部调用它的函数?

2 个答案:

答案 0 :(得分:1)

将函数绑定到正确的上下文:

function fadeOutAnimation()
{
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        this.objectToggle();
    }.bind(this));

}

或者只是存储对this的引用:

function fadeOutAnimation()
{
    var that = this;
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        that.objectToggle();
    });

}

答案 1 :(得分:1)

内部动画函数this指的是this的动画div和上下文已更改。你可以绑定它或者可以在代码前面保存引用

function fadeOutAnimation()
{
    that = this;
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        that.objectToggle();
    });

}