Reputation: 11830
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?
Upvotes: 4
Views: 12457
Reputation:
var
s in constructor
are only defined in the scope of the constructor""
is a string that is present in the global scope
. Not finding name
in the current scope of the method execution, it is finded moved up to the window.name
. Try to change name with something else (ex: name2
) and You'll get an error."somexyz"
see the snippet belowclass something {
constructor() {
var name = "somexyz"
var name2 = "somexyz"
this.age = 13
}
somefunc () {
console.log(this.name)//undefined
console.log(name) //window.name
console.log(window.name) //window.name
console.log(this.__proto__.constructor.name) //"something"
console.log(this.age) //13
}
}
let foo = new something()
foo.somefunc()
Upvotes: 1
Reputation: 1156
The emphasis should be on "simple class" - the notion of a local variable seems pointless but it's actually very useful.
Simple example - when you reuse a variable repeatedly
class transport
{
constructor ()
{
const someString = "IUseThisAgainAndAgain";
this.type = 'someType';
this.name = 'someName';
this.serial = someString + "SOMETHING";
this.model = someString + "something thing";
this.example = someString + "another string concat";
}
}
As you can see we use someString
alot. And you will see constructor method that are huge and having a variable for a repeated instance will allow better readability of code and allow you to easily modify the instance in one place.
Upvotes: 3
Reputation: 721
You can use variables to set a default value also for checking purposes or mathematical calculations.
For example:
class something {
constructor(age) {
var default_age = "13";
if(age > 13){
this.age = age;
}else{
this.age = default_age;
}
}
myage() {
console.log("I am "+this.age+" years old.")
}
}
var newobj = new something(15);
newobj.myage();
var newobj2 = new something(8);
newobj2.myage();
Upvotes: 2