Javascript 函数实例和调用

Javascript Function Instance and call

本文关键字:调用 实例 函数 Javascript      更新时间:2023-09-26

我使用Javascript,我想创建授权类。

我的代码是

function Auth() {
    this.action;
    this.run = function() {
        $("#auth-dialog-id").dialog({
            width: 400,
            height: 250,
            modal: true,
            buttons: {
                OK: function() {
                    this.action();
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        });
    };
}

    auth = new Auth();
    auth.action = a;
    auth.run();
}
function a() {
    alert("test");
}

但我有错误

对象 # 没有方法"操作"

有人可以帮助我吗?

由于您已经更正了this.action = a问题,因此问题出在OK按钮回调上下文中。在按钮内单击回调this不引用auth实例。

这里一个可能的解决方案是使用闭包变量,如下所示

function Auth() {
    var self = this;
    this.run = function () {
        $("#auth-dialog-id").dialog({
            width: 400,
            height: 250,
            modal: true,
            buttons: {
                OK: function () {
                    self.action();
                    $(this).dialog("close");
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    };
}
auth = new Auth();
auth.action = a;
auth.run();

演示:小提琴