Understanding ***THIS***

const video = {
  title: 'a',
  play() {
    console.log(this)
  }
}
console.log(video) // -- > { title: 'a', play: [Function: play] }
video.play() // --> { title: 'a', play: [Function: play] }

Since these two results are the same, why would I need this to call an object it’s in? I’ve been watching several tutorials and I can’t find anyone that has explained that .

Probably the most common use of this is for methods to reference object-level data.

For example:

const checklist = {
    const list= [];
    checkDone () {
        if (this.list.length === 0) {
            console.log("All done with your chores!");
            this.throwConfetti();
        else {
            console.log("More work to do.");
            this.sadTrombone();
        }
    }
   // other methods like throwConfetti, sadTrombone, addTask, removeTask, etc
}        
1 Like

What happens if you change it to this:

const video = {
  title: 'a',
  play() {
    console.log(video)
  }
}

Now run video.play()

Bear in mind this is an example, and that play would probably play the video whose information is stored in the object.

You need a way to be able to refer to an object when the code that is running is from inside the object. What if you have millions of video objects? If you run play on one of them, how does that particular object do its own thing?