Where is my function? (this)

Hello!
Can someone help me to understand why I can’t see the playMeow() when I call this inside handleKey()?
When I console, this is returning me the Window component :thinking:

class App extends React.Component{
  constructor(props){
    super(props); 
    this.state = {
      display:""
    }
    this.handleKey = this.handleKey.bind(this);
    this.clearDisplay = this.clearDisplay.bind(this);
    this.playMeow = this.playMeow.bind(this);
    this.showMsg = this.showMsg.bind(this);
  }
  
  componentDidMount(){
    document.addEventListener("keydown", this.handleKey);
  }
  
  componentWillUnmount(){
    document.addEventListener("keydown", this.handleKey);
  }
  
  playMeow (e){
    console.log("playing")
    let sound = document.getElementById(e.target.children[0].id);
    sound.currentTime = 0;
    //sound.play();    
    this.showMsg(sound.id);
    setTimeout(() => this.clearDisplay(), 2000);
  }
 handleKey(e){
    let keyPressed = e.keyCode;
    let keyPlay = [document.getElementById("paws")];
    let arr = Array.prototype.slice.call(keyPlay[0].children);   
    arr.map(function(e){
     (e.id == meowBank.id) ?  this.playMeow : console.log('test ',this)
    });   
  }

Thanks!

I might change the callback in arr.map(...) to a fat arrow function: (e)=>{...} – using a fully defined function may be throwing you out of the handleKey’s bound context.

1 Like

Worked! Thank you very much!

The reason that works is, in part, the nature of the fat arrow function. It runs the function without changing the current context/scope, so any local variables (and this) remain accessible within the function. I might suggest taking a look on the MDN in your spare time, reviewing them. Not sure what the technical name is, I’ve always heard them referred to as ‘fat arrow functions’.

1 Like