简体   繁体   English

Javascript对象访问其属性

[英]Javascript object accessing it's properties

I am trying to create an object in javascript that has an animation run which calls another method when it finishes. 我正在尝试用JavaScript创建一个具有动画运行的对象,该对象在完成时会调用另一个方法。

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; }
}

A whole lot has been cut for brevity and this code does work when it isn't inside an object and uses global variables. 为了简洁起见,已经削减了很多内容,当该代码不在对象内部并且使用全局变量时,此代码也可以工作。 The alert runs, but animating isn't changing. 警报运行,但是动画没有改变。

variables. 变量。

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; }
}

Inside of this.doAnimate add a $.proxy. this.doAnimate内部添加$ .proxy。

var callback = $.proxy( this.endAnim, this );

$("#panel" + this.focusedPanel).animate({width:"115px"},1000, callback);

Basically the problem is you lose your this value when you assign it to a callback like this. 基本上,问题是当您this值分配给这样的回调时,会丢失this值。 proxy will make sure the function is called with the proper this . 代理将确保使用正确的this调用该函数。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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