Code:
car = {
currentSpeed = 10
accelerate(){
this.currentSpeed = this.currentSpeed + 1;
}
}
print(car.currentSpeed) //this prints 10
car.accelerate()
print(car.currentSpeed)//this prints 11
Here, the keyword "this" refers to the car object, as that is the object the accelerate method is part of. Simple enough so far. Lets say, that for some reason another object can also make this car go faster. (Maybe its engine broke and is being pulled or something). In those cases we can just pass the accelerate function to the object that will make it go faster
Code:
pullingCar = {
accelerateCar = car.accelerate
}
In normal languages the work "this" in car.accelerate still points to the car object so when we do
Code:
print(car.currentSpeed)//this now prints 11 (from last time)
pullingCar.accelerateCar()
print(car.currentSpeed) //and now it prints 12, as the car got faster.
However, in JS that isn't quite the case. Instead "this" now suddenly refers to pullingCar instead of car. Why? Ask the guy that designed it/the guy that asked for JS to be created in 10 days.
Anyway. The work around is to not copy the method but instead of putting an so called "arrow" function around it. Which would make the code more like
Code:
pullingCar = {
accelerateCar = ()=>car.accelerate()
}
Now, this may not sound too bad. But lets say you also want to have something else happen in the accelerateCar method, considering its already wrapped in another method anyway. You may think that something like
Code:
pullingCar = {
accelerateCar = ()=>{
car.accelerate()
this.doSomethingElse()
}
}
Would do the trick. However, it isn't. Because in these examples we used an object dirrectly. MEANING that the keyword "this" INSIDE the arrow function does NOT point "pullingCar" because that did not exist yet when we made that function. INSTEAD it points to whatever "this" refers to in the code that created pulling car. Or in our case its the so called "window" object AKA the thing where all our globals are stored.