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.

2
  • 2
    Have you tried using both? Didn't you notice any difference? Commented Aug 2, 2018 at 6: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); Commented Aug 2, 2018 at 6:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Titian Cernicova-Dragomir, Yeah i observed the same behavior. Any other major difference ?
Thanks for helping me out. I understood the difference. Also pointing out the use of Object.defineProperty helped.
@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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.