Skip to content Skip to sidebar Skip to footer

I'm Trying To Better Understand The Use Of `this`. The Example Is Verbose, But Its For The Purpose Of Trying To Better Understand

I'm trying to better understand the use of this. In experimenting with this code, I found I can access the items in arr by using something like console.log(this.arr[4]), but only i

Solution 1:

In a browser, top-level this is window, and top-level var declarations also make variables accessible as properties of window, while let and const do not. The correct way to reference arr is simply

console.log(arr[4])

I would discourage you from using top-level this to even access var declarations, because code which relies on that behavior of var is obviously confusing, as this case is a perfect example of.

Solution 2:

The behavior you're getting confused about is not specific to 'this'. It is related to scope. 'var' has a different scope than 'let' or 'const'.

var - has function level scoping and can change the value reference
let - has block level scoping and can change the value reference
const - has block level scoping but cannot change the value reference

https://love2dev.com/blog/javaScript-var-let-const/

Be precise about how and where you declare your variables as this is an important part of JavaScript syntax/interpretation.

Post a Comment for "I'm Trying To Better Understand The Use Of `this`. The Example Is Verbose, But Its For The Purpose Of Trying To Better Understand"