Search code examples
javascriptfunctionprototypeaddeventlistener

Javascript: prototype function, changing variables - becomes NaN


With this code, when pressing a key, 'index' become NaN. Why, and how to do it correctly?

const Key = function(){
    this.Index = 0;
}

Key.prototype.storeKey = function(key){
    this.Index++;
    console.log(this.Index);
}

const listener = new Key();

addEventListener("keydown", listener.storeKey);     // <---- does not work

listener.storeKey();    // <--- does work   

change value in object by eventlistener prototype function


Solution

  • Try this code :

    const Key = function() {
      this.Index = 0;
    };
    
    Key.prototype.storeKey = function(key) {
      this.Index++;
      console.log(this.Index);
    };
    
    const listener = new Key();
    
    addEventListener("keydown", listener.storeKey.bind(listener)); // Bind 'this' to the 'listener' object
    
    listener.storeKey(); // Works fine