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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With