JohnSnow
JohnSnow

Reputation: 7121

'this' keyword not being reassigned by function.prototype.call

consider this module:

//Adder component
(function init() {

//Initilize variables
const addButton = document.getElementById('add-btn');
const userInput = document.getElementById('user-input');
const userOutput = document.getElementById('user-output');

const App = {
    //Register event handlers
    registerHandlers() {
        addButton.addEventListener('click', function () {
            this.addKeyValue.call(App, userInput.value);
        });
    },

    addKeyValue(input) {
        userOutput.value = input;
    },

};

App.registerHandlers();

})();

When the click event is fired this fails because this.addKeyValue is undefined because at the run time of that function this is referring to the input element and not the App object. But isn't that what the Function.prototype.call function is for? Why is my call function not binding this to App?

Upvotes: 1

Views: 34

Answers (1)

Quentin
Quentin

Reputation: 944545

But isn't that what the call function is for?

No.

this.addKeyValue.call will get the value of this.addKeyValue, which needs to be a function, then call it. The value of this inside that function call will be what you specify.

It doesn't change the value of this before you call the call function. You can use bind for that.

addButton.addEventListener('click', function () {
    this.addKeyValue(userInput.value);
}.bind(App));

Upvotes: 3

Related Questions