Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Advantages of Setters/Getters?

I am a backend developer that has developed mostly in Java so I was taught to use setters/getters instead of directly accessing the properties of a class.

Now I'm getting into the frontend world and now got to js/ts. I've seen lot of people access object variables directly without setters and getters as you'd do in Java such as this.person.name.

Why is this? Is there any advantage on using getter/setter on ts and js if you don't need to add extra code but just to get the value or set it?

Thanks.

like image 205
Wrong Avatar asked Sep 06 '18 13:09

Wrong


People also ask

What is getters and setters in typescript?

#typescript Typescript Tips (2 Part Series) 1Template Literal Types in TypeScript 4.12TypeScript Getters and Setters TypeScript supports using getters and setters in classes. This enables you to create properties on a class that can be retrieved or assigned dynamically.

What is the use of getters and setters?

To avoid repeating the check, you can use setters and getters. The getters and setters allow you to control the access to the properties of a class. A getter method returns the value of the property’s value. A getter is also called an accessor.

Are getter and setter functions easier to parse?

Once you get this set of intent down, code written with Getter and Setter functions will become easier to parse. Here’s an example where we get a value, set a value, and run a process – all done with functions. And here’s the same version with Getter and Setter functions.

What is the use of setters in JavaScript?

As you can see from the code, the setters are useful when you want to validate the data before assigning it to the properties. In addition, you can perform complex logic. The following shows how to create the fullname getter and setter.


2 Answers

A difference between using a getter or setter and accessing object variables directly is that getters/setters are automatically invoked on assignment. So it looks just like a normal property but behind the scenes you can have extra logic (or checks) to be run just before or after the assignment.

So if you decide to add this kind of extra logic to one of the existing object properties already has references, you can convert it to getter/setter style without altering the rest of the code that has access to that property.

let person = {
    _age: 50,

    set age(newage){
      if(typeof newage === 'number'){
           this._age = newage;
            console.log('valid input')
      }
      else{
           console.log ('Invalid input');
      }
    }

  };
like image 90
عبدالرحمان Avatar answered Oct 08 '22 02:10

عبدالرحمان


@Pointy is wrong to say: it's really a good idea to forget everything about Java when learning JavaScript. Encapsulation is an object oriented principle of hiding the internal state and behaviour of an object, making your code more maintainable.

In javascript you make tings work with no/messy structure. Typescript is a superset of javascript, this guy is your friend if you are a C#, Java or any other object oriented language programmer.

Example:
in myobject.Ts

export class MyObject {

   // private property
   private _x: number;
   private _z: number;

   // public property
   y: number;

   constructor(private _d?: number) {
       this._x = 0;
       this.y = 0;
       this._z = 0;

       this.clog(_d)
   }

   // access modifier only for _x
   get x() {
       return this._x;
   }
   set x(value: number) {
       this._x = value;
   }

   private clog(d: number) { 
       console.log(d);
   }

   // arrow function -> public
   testf = () => { console.log('value of this._d' , this._d); }
}

then you get in myobject.js this:

export class MyObject {
   constructor(_d) {
       this._d = _d;
       // arrow function -> public
       this.testf = () => { console.log('value of this._d', this._d); };
       this._x = 0;
       this.y = 0;
       this.clog(_d);
   }
   // access modifier
   get x() {
       return this._x;
   }
   set x(value) {
       this._x = value;
   }
   clog(d) {
       console.log(d);
   }
}

Let's use it in main.Ts:

import { MyObject } from './myobject';

let mo = new MyObject(15);

// set a value to the private property x
mo.x = 5;

// get the value of the private property x
// output 5
console.log(mo.x);

vscode and intellisense:
enter image description here

with intellisense in vscode you see that it does not show the private property _z and the private function clog().

I suggest you to watch this tutorial and make a better idea. Link

👍

like image 42
Sinan Avatar answered Oct 08 '22 01:10

Sinan