我有以下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
我的问题是如何为它提供对象的引用,从而允许我从回调函数内部调用它的函数?
答案 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();
});
}