Javascript OOP - 对象如何调用其实例方法?

mas*_*san 3 javascript oop

我用OOP写了我的第一个Javascript.我试图从同一个对象中的另一个方法调用它的实例方法.

当我调用关闭对话框后触发的下面的begin()方法时,我得到了 "this.after() is not a function".

如果像Java这样的其他语言,它应该只是处理没有任何问题.有什么我想念的吗?

我正在使用jQuery bind()进行对话关闭事件,因此"this"必须指向不是类本身.

function MyHandler() {

    this.begin = function() {
            $("#hiddenIframe").dialog({
                autoOpen: true,
                height: 300,
                width: 300
            });


            $("#hiddenIframe").bind("dialogclose", function() {
                this.after();
            });
    }

    this.after = function() {
        //do something here
    }
}

var myInstance = new MyHandler();
myInstance.begin(); //error: this.after() is not function ???
Run Code Online (Sandbox Code Playgroud)

Igo*_*gor 5

试试这个:

function MyHandler() {

    var thisInstance = this;

    this.begin = function() {
        $("#hiddenIframe").bind("dialogclose", function() {
             thisInstance.after();
        });
    }

    this.after = function() {
        //do something here
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你,Juicy Scripter.我不知道jquery如何dialog调用dialogclose事件处理程序,但是所描述的错误表明匿名函数的调用上下文this.after();不是MyHandler,并且this意味着其他东西.要明确哪个方法after是,在MyHandler构造函数中定义局部变量,并在需要调用MyHandler将在未知上下文中调用的函数内的实例方法时使用此变量.