K
K
Kirill Ozeretskovsky2020-01-26 13:40:16
JavaScript
Kirill Ozeretskovsky, 2020-01-26 13:40:16

Why can't the functions (methods) of a module (Module design pattern) be used in event handlers?

There is the following, very simple, at first glance, code:

"use strict";
let TaskModule = (function () {
    return {
        msg: function () {
            return "Hello World!";
        }, 
        showMsg: function () {
            alert(this.msg());
        },
        doTask: function () {
            this.showMsg(); //Строка №11
        }      
    }
})();
(function() {
    let addButtonElement = document.getElementById("add-task-btn");
    addButtonElement.addEventListener("click", TaskModule.doTask, true); 
})();

But, when the button click event occurs, the following message is displayed in the developer console:
Uncaught TypeError: this.showMsg is not a function
at HTMLInputElement.doTask (main.js:11)

However, if we call the module function through the "wrapper" function and pass the name of the "wrapper" function to the event handler, then everything works as it should:
"use strict";
let TaskModule = (function () {
    return {
        msg: function () {
            return "Hello World!";
        }, 
        showMsg: function () {
            alert(this.msg());
        },
        doTask: function () {
            this.showMsg();
        }      
    }
})();
(function() {
    let addButtonElement = document.getElementById("add-task-btn");
    let doTaskFn = function() {
        TaskModule.doTask();
    }
    addButtonElement.addEventListener("click", doTaskFn, true);

   
})();

Question : why and what should be read to understand the meaning?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-01-26
@OZKA

This is because this points to the context of the call, not the context of the declaration. That is, in different situations, this is different entities. Read this .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question