class logic questions

Hey, a few questions about the logic in classes- 1) If i define a this. variable inside of a function, why can i use it outside of the function globally within the class? I understand it's because it uses this. and that refers to the object but that defies the regular logic of how that would work, is that specific functionality for this or classes? (example: https://codepen.io/deerCabin/pen/xbKYQPG) 2) Why don't i need to use const or var when defining this. variables? 3) Why don't i need to use the function keyword when defining functions within classes? Thanks in advance.
14 Replies
ἔρως
ἔρως2w ago
this is a special variable in fact, it's a keyword
snxxwyy
snxxwyyOP2w ago
oh okay that makes sense then. so it's all just a functionality of that keyword essentially? how about the function keyword? (3))?
ἔρως
ἔρως2w ago
that's because classes are syntax sugar for objects without prototype whoever at ecma decided that classes should be like that made it into the standard you also don't need to use var for properties
snxxwyy
snxxwyyOP2w ago
hm okay i see, thanks for the help
ἔρως
ἔρως2w ago
i know it is weird, but, sometimes the answer is "someone decided it for some reason"
snxxwyy
snxxwyyOP2w ago
yeah js seems to have these little curveballs in a lot of places haha
ἔρως
ἔρως2w ago
it does, and it is funny as hell but i can see why they skipped the function and var keywords if it has parenthesis, it's a function - otherwise it's a variable
snxxwyy
snxxwyyOP2w ago
I mean that does make sense but definitely throws you off when in other places those are needed
ἔρως
ἔρως2w ago
arrow functions fix that
snxxwyy
snxxwyyOP2w ago
arrow functions need the () => which is equivalent to function in its own case right? Unless you mean in another way?
ἔρως
ἔρως2w ago
in this situation, yes but arrow functions don't change the value of this
snxxwyy
snxxwyyOP2w ago
Oh right yeah I see, you’d have to use .bind for keeping the value of this for regular functions right?
ἔρως
ἔρως2w ago
no, that's to change the value of this you can temporarily change the value with .call() and .apply()
snxxwyy
snxxwyyOP2w ago
ah okay

Did you find this page helpful?