简体   繁体   中英

object callback function is undefined Javascript

i have the following 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();
}

From inside my animate function i am called this.objectToggle();

However when it completes the animation i get undefined is not a function

I am quite certian that it is because of the inner callback function that does not have a reference to the object

My question is how can i give it a reference to my object and thereby allow me to call its functions from inside the callback function?

Bind the function to the right context:

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

}

Or just store a reference to this :

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

}

Inside animate function this refers to the animating div and context of the this has changed. you can bind this or can save reference earlier in the code

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM