Javascript对象访问它';s属性
我试图在javascript中创建一个对象,该对象有一个动画运行,当它完成时调用另一个方法Javascript对象访问它';s属性,javascript,object,Javascript,Object,我试图在javascript中创建一个对象,该对象有一个动画运行,当它完成时调用另一个方法 function panel_manager() { this.animating = false; this.doAnimate = function (nPanel) { //if we're still moving panels, do nothing if(this.animating) return; this.animati
function panel_manager() {
this.animating = false;
this.doAnimate = function (nPanel) {
//if we're still moving panels, do nothing
if(this.animating) return;
this.animating = true;
//enlarge new panel
$("#panel" + this.focusedPanel).animate({width:"115px"},1000, this.endAnim);
}
this.endAnim = function () { alert("called"); this.animating = false; }
}
为了简洁起见,这段代码做了大量修改,当它不在一个对象中并且使用全局变量时,这段代码就可以工作了。警报将运行,但动画设置不会更改。在
this.doAnimate
中添加$.proxy
var callback = $.proxy( this.endAnim, this );
$("#panel" + this.focusedPanel).animate({width:"115px"},1000, callback);
基本上,问题是当您将这个值分配给这样的回调时,它会丢失。代理将确保使用正确的this
调用函数
干杯 变量
function panel_manager() {
var that = this;
this.animating = false;
this.doAnimate = function (nPanel) {
if(this.animating) return;
this.animating = true;
$("#panel" + this.focusedPanel).animate({width:"115px"},1000, that.endAnim);
}
this.endAnim = function () { alert("called"); that.animating = false; }
}
$(“#面板”+这个.focusedPanel).animate(blah,1000,这个.endAnim)代码>我认为这是我的问题,只是找不到任何解决方案。谢谢,它现在可以工作了。你在闭包中,当你只能使用变量时,不要使用$.proxy。请详细说明,AutoSponge。谢谢。看来一个有效的例子和问题的答案不需要否决票。但是是的,这是有效的,你肯定是个英雄。谢谢。sci1,这不是针对个人的。您提供了一个不应该被模拟的完美反模式——当一个简单变量可以使用时,使用框架方法。除了性能,这只是对作用域如何工作的一个简单理解。工作,我假设这样做的开销/处理更少。我要指出的是,优化的机会更多(主要是缓存“panel”对象),但我希望OP能够看到实现所需结果所需的细微差别。代理(或Function.prototype.bind)在共享函数时更常用——此函数只属于单个实例,因此为闭包确定变量的范围是完全正确的。