Skip to content

Commit fcab35e

Browse files
committed
Update README.md
1 parent bb4235d commit fcab35e

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

README.md

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -123,22 +123,33 @@ new MyClass().myReadonlyProperty = 5; // error, readonly
123123

124124
## Q. What is getters and setters in TypeScript?
125125

126-
TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives a way of having finer-grained control over how a member is accessed on each object.
126+
TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. Getters enable us to bind a property to a function that is called when the property is accessed, whereas setters bind a property to a function that is called on attempts to set the property.
127+
128+
**Example:**
127129

128130
```ts
131+
/**
132+
* Getters and Setters
133+
*/
129134
class Employee {
130-
131-
private _name: string;
132-
133-
get Name() {
134-
return this._name;
135-
}
136-
set Name(val) {
137-
this._name = val;
138-
}
135+
private _name: string;
136+
137+
get Name() {
138+
return this._name;
139+
}
140+
set Name(val) {
141+
this._name = val;
142+
}
139143
}
144+
145+
let employee = new Employee();
146+
employee.Name = "Pradeep";
147+
148+
console.log("Name" + employee.Name); // Pradeep
140149
```
141150

151+
**⚝ [Try this example on CodeSandbox](https://codesandbox.io/s/getter-and-setter-peq1nj?file=/src/index.ts)**
152+
142153
<div align="right">
143154
<b><a href="#">↥ back to top</a></b>
144155
</div>

0 commit comments

Comments
 (0)