I was studying class based structure in Javascript
To say the least, I created a simple class
class something {
constructor() {
var name = "somexyz"
this.age = 13
}
somefunc () {
console.log(this.name)//Undefined
console.log(name) //blank space
console.log(this.age) //13
}
}
And then call it using
let foo = new something()
foo.somefunc()
Which consoles.log (mentioned in comments of above code) 1. undefined 2. empty space 3. 13
or take a constructor function
function something () {
this.age = 11
let age = 13
this.getAge = function () {
return this.age
}
}
Here,
let somethingNew = new something()
Will return age as 11
Now, my question is what exactly is the purpose of having variable in constructors then?
thiscreates "instance" data - - data that is part of the instance of the object you make.let,var, &constcreate regular variables that do not store their data along with the instance and therefore you can't access their information from the instance variable. They exist as ways to create "private" data.