r/learnjavascript • • Dec 18 '22

Cannot understand "this" keyword

My head is going to explode because of this. I watched several videos, read articles from MDN, W3schools, and TOP, and I still can't understand.

There's so many values and scenarios around it and I feel like they're explained so vaguely! I struggle to get familiar with it. Can someone drop their own explanation?

90 Upvotes

58 comments sorted by

View all comments

Show parent comment

2

u/dotpr Dec 19 '22

Is it just me or this doesn't help much for case #2? Like, it's almost as easy as function with parameters in parentheses

Instead of being between the parentheses like other parameters, it is the the thing to the left of the dot

1

u/delventhalz Dec 19 '22

It is almost identical in terms of how it works, and if you are writing bare functions like in my examples you would almost always just use normal function parameters. Where this actually gets used is with classes.

class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log('Hello,', this.name);
  }
}

If you don't write code with classes, then are unlikely to ever use this.