12

I was following a tutorial on Typescript Classes and the person teaching created a class and some setter/getter methods.But when i read Typescript Documentation the approach was somewhat different. Can someone help me understand the difference between both approaches.

Approach 1:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

getName = (): string => {
    return this._name;
}

setName = (name: string) => {
    this._name = name;
}
}

Approach 2:

class Student {
private _name: string;

constructor(name:string) {
    this._name=name;
}

public get name(): string {
    return this._name;
}


public set name(value: string) {
    this._name = value;
}
}

Have a look. In Approach 1 we write getter/setter as normal functions But in Approach 2 the keyword get/set is used. Can someone help me understand the difference between both approaches.

Raj Thakur
  • 323
  • 1
  • 3
  • 12
  • 2
    Have you tried using both? Didn't you notice any difference? – JB Nizet Aug 02 '18 at 06:13
  • 1
    Yeah i tried using them both. And the difference i can see is . In Approach 1: I can use for example : myStudent.setName("ABCD"); console.log(mystudent.getName()); But in Approach 2 what i can do is myStudent.name="XYZ"; console.log(stu.name); – Raj Thakur Aug 02 '18 at 06:15

1 Answers1

17

The difference in the way you use them. In the first case you need to explictly call the get/set methdods. In the second you can use name like an actual field on the class and the runtime will call the get/set accessors automatically.

Consider the simple example of appending a character to the name:

Approach 1

let s = new Student();
s.setName(s.getName() + "A") // we need to explicitly call the get/ set methods

Approach 2

let s = new Student();
s.name += "A" // we can use += and the get/set accessors will get called for us

Behind the scene the get/set accessor approach (approach 2) will use Object.defineProperty

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • Hi Titian Cernicova-Dragomir, Yeah i observed the same behavior. Any other major difference ? – Raj Thakur Aug 02 '18 at 06:20
  • Thanks for helping me out. I understood the difference. Also pointing out the use of Object.defineProperty helped. – Raj Thakur Aug 02 '18 at 06:24
  • 1
    @RajThakur That would be the main difference, I can't think of anything else taht would be important (except that approach 2 is not supported if you target es3 and might not work in very old browsers) – Titian Cernicova-Dragomir Aug 02 '18 at 06:55