What exactly is "this"?
Did the this.img = img;
line trip you up? Here's what's going on with that.
The Card
class has an instance variable called img
. We're also passing an argument to its constructor function with the exact same name, img
. If we simply wrote img = img;
, that means we'd be setting the value of the argument to the value of the argument. Hunh! That's not quite what we're after.
By specifying this.img = img;
, we're saying that we want the img
variable attached to this, the Card
class, to have the same value as the argument called img
.
It's a smidge confusing, I'll admit. So, why not just call the argument something different? You absolutely could! We did it this way because it's very common to see variables passed to the constructor function with the same name as the instance variables in the class. You may as well encounter it here with a full explanation, than come across it in the wild and let it gnaw your leg off.
Here's one more look at another, completely imaginary class...