从类内部的构造函数调用函数

时间:2018-12-12 17:50:32

标签: javascript javascript-objects

我创建了以下课程:

class GlobalModal {
    constructor(text) {
        this.modal = document.getElementById('Modal');
        this.span = document.getElementById("closeModal");
        this.text = text;

        //Show the GlobalModal
        this.modal.style.display = "block";

        // When the user clicks on <span> (x), close the modal
        this.span.onclick = function() {
            this.close();
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == this.modal) {
                this.close();
            }
        }
    }

    // Function to close the GlobalModal
    close() {
        this.modal.style.display = "none";
    }
}

我正在尝试调用函数this.close();

错误:此功能不是关闭功能。

我想做的甚至有可能吗?我在做什么错了?

2 个答案:

答案 0 :(得分:2)

如果要在回调中使用img.sum(axis=2, keepdims = True),则应使用将this绑定到词法上下文的箭头函数:

this

答案 1 :(得分:1)

class GlobalModal {
    constructor(text) {
        this.modal = document.getElementById('Modal');
        this.span = document.getElementById("closeModal");
        this.text = text;

        //Show the GlobalModal
        this.modal.style.display = "block";

        // When the user clicks on <span> (x), close the modal
        this.span.onclick = function() {
            this.close();
        }.bind(this)

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == this.modal) {
                this.close();
            }
        }.bind(this)
    }

    // Function to close the GlobalModal
    close() {
        this.modal.style.display = "none";
    }
}

正如@ibrahim mahrir指出的那样,您在事件侦听器中丢失了this的上下文。 bind明确将this的值设置为您提供的任何参数。