+ 1

Difference between this.var; vs let var; in JavaScript?

//in JavaScript OOP //in know about the new 'Class' in es6 still need to clear fundamentals let Cname = function(){ this.prop1 = "some val"; let prop2 = "other val"; } //what is the difference between the above variables or is it a good practice or not

29th Aug 2020, 1:34 PM
Utkarsh Dhiman
Utkarsh Dhiman - avatar
2 Answers
+ 2
"this" is a reference variable, it refers to the object the Cname belongs to. Here right now Cname belongs to the window object that is a global object.. As soon as you instantiate an object of the Cname, then this will point to that object.. for ex : let obj = new Cname(); now "prop1" and "prop2" points to the "obj" object. or if you just call: Cname(); then the "prop1" and "prop2" belongs to the window object. And "let/const" are another way to define variable, but if you create a variable with "var/let/const" locally you cannot directly use it globally or outside that block so we use "this" on purpose, when we need to create objects or have dynamic usage.. otherwise we always use "let" and "const"
29th Aug 2020, 2:48 PM
ŠœŠ³. ŠšŠ½Š°ŠæšŸŒ 
ŠœŠ³. ŠšŠ½Š°ŠæšŸŒ  - avatar
+ 6
It's not about best, it's about what to need to use. When you want to define something as property of that class or constructor function you use 'this' and let/const for normal variables. https://code.sololearn.com/WkSGhPmj9uB6/?ref=app
29th Aug 2020, 1:41 PM
Raj Chhatrala
Raj Chhatrala - avatar