Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of declaring variable inside constructor

Tags:

javascript

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?

like image 453
iRohitBhatia Avatar asked Oct 27 '25 17:10

iRohitBhatia


1 Answers

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.

like image 125
Mudassir Avatar answered Oct 29 '25 06:10

Mudassir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!