使用在对象中传递的匿名函数

时间:2016-12-28 18:45:46

标签: javascript ecmascript-6

我使用的是ES6,因为它的语法类功能类似于Java。

我想使用在对象构造函数中传递的函数。

class DialogOkCancel extends Dialog {

    constructor(title, okEvent, cancelEvent) {
        super(title);
        this._okEvent = okEvent;
        this._cancelEvent = cancelEvent;
    }

    buildDialog() {
        super.buildDialog();

        $("#" + this._id).dialog({
            buttons: [
                {
                    text: "Ok",
                    click: this._okEvent
                },
                {
                    text: "Abbrechen",
                    click: this._cancelEvent
                }
            ]
        });
    }
}

这是我的目标代码。

var dialog = new DialogOkCancel("test", function () {
        alert("Ok");
    },
    function () {
        alert("Cancel");
    });

我可以使用变量okEvent和cancelEvent及其成员变量。但是当我离开范围时,脚本引擎会说未定义或不是函数。

我也尝试过:

buildDialog() {
    super.buildDialog();

    var that = this;
    $("#" + this._id).dialog({
        buttons: [
            {
                text: "Ok",
                click: that._okEvent
            },
            {
                text: "Cancel",
                click: that._cancelEvent
            }
        ]
    });
}

对话类:     class Dialog {

    constructor(title) {
        this._id = IdGenerator.generate();
        this._title  = title;
        this._dialog = document.createElement("div");
        this._dialog.setAttribute("id", this._id);
        document.body.appendChild(this._dialog);
        this.buildDialog();
    }

    getId() {
        return this._id;
    }

    getTitle() {
        return this._title;
    }

    getDialog() {
        return this._dialog;
    }

    buildDialog() {
        $("#" + this._id).dialog({
            autoOpen: false,
            //width: 400,
            hide: { effect: "scale", duration: 200 },
            modal: true,
            show: { effect: "blind", duration: 200 },
            title: this._title
        });
    }
}

0 个答案:

没有答案