Justas
Justas

Reputation: 101

How can I reach object values or functions from my method function?

How can I reach values or functions in my object from my methods function?

Example:

function Game(playerName) {
  this.player = playerName;
  this.scoreWins = 0;
  this.scoreLoses = 0;

  this.getCheckLetter = function () {
    document.onkeyup = myKeyUpHandler;

  function myKeyUpHandler() {
    firstName = this.player;
    console.log(firstName);
    }
  }
}

Upvotes: 0

Views: 56

Answers (1)

Jhecht
Jhecht

Reputation: 4435

First is that you should tend to use [element].addEventListener(...) instead of document.on[event name] as some script could remove your event listener on accident later on.

Next is that when you bind an event listener, the this inside the event listener function becomes the element that the event listener is on. In order to avoid this, you must specifically bind the function to another object. In thise case, I bind the this.myKeyUpHandler to this, aka the Game object.

The output of you hitting keys on after focusing the document is that you receive some console notifications with the initiated player's name.

function Game(playerName) {
  this.player = playerName;
  this.scoreWins = 0;
  this.scoreLoses = 0;
  
  this.myKeyUpHandler= function() {
    firstName = this.player;
    console.log(firstName);
  }

  document.addEventListener('keyup', this.myKeyUpHandler.bind(this));
  
}

let Paul = new Game("Paul");

Upvotes: 1

Related Questions