I'm learning Javascript, and I'm a little confused about the "this" keyword. I understand it refers to the specific instance of an object if it's called (i.e. if fido = new Dog("Fido"), then this.method will refer to the specific object it's called on).
However, I was doing a problem off of Javascript.info, and they had the following solution for implementing a Delay wrapper to the Function prototype:
Function.prototype.defer = function(ms) {
let f = this; //*****
return function(...args) {
setTimeout(() => f.apply(this, args), ms); //****
}
};
// check it
function f(a, b) {
alert(a + b);
}
f.defer(1000)(1, 2); // shows 3 after 1 sec
I'm confused about the use of "this" in the solution. In the first call, (let f = this), it sets f to the specific call of the function. However, 2 lines after, they call f.apply(this, args). I'm confused why they used both the variable f, as well as the actual "this" keyword here... what is the difference in what they refer to?
Thanks!
Edit: The exercise says it's not good practice to change the prototype, but it's there just to test your understanding
Edit2: I've also tried using console.log(this), and it shows up undefined. I'm curious why I need it at all (inputting " " instead of "this" actually yields the same result, which is why I am confused)