I am trying to understand how "this" keyword works and trying to increase the count variable using a function. But If i use let to declare count, count does not increase, but if i use var to declare count it works. I don't know why is this happening.
let count = 0;
function increaseCounter() {
this.count++;
};
increaseCounter()
console.log(count)
The function and variable is not in a class
, which means you do not need to use the this
keyword. You can omit it and just use count++;
.
If the function and variable is in a class, then the this
keyword is necessary.
Since the code is not working for you, that means you are not in a class, and you should use the first option. The let
keyword does not affect this.
For more information, I recommend checking out Classes , Let vs. Var , and The this
Keyword
The this
keyword in JavaScript refers to the object that is currently executing the code. In the case of a function, the this
keyword refers to the object that the function is a property of.
In your case, you are trying to increase the value of the count variable by using the this
keyword inside the increaseCounter
function. However, the count variable is not a property of any object, so the this keyword inside the function is not referencing the count variable as you'd expect.
this
has a different context depending where it is being used. Check out W3 for a good explanation.
As far as the let
vs var
problem. Each have a different scope. Read this post about that.
"var" is global scoped whereas let is function scoped. Thats why when you "var", the "this" which you used inside the function can find property "count" which is available globally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.