Getter & Setter
In This Section, We will study about Accessor Property.
Accessor Property are methods that are used to get or set the value of Object.
Accessor Property does exactly what you have learned in previous sections to get and set new methods and properties.
But, There are many Benefits of Using Get & Set
Why Using Getters and Setters?
- It makes the syntax simple.
- It is useful for getting and setting properties directly in the Objects.
- It makes data better and secure.
Declaration
In Accessor Property We have 2 Keywords get and set
get - It is used to get the properties of Objects, this method is known as Getter method.
set - It is used to set the properties of Objects, this method is known as Setter method.
Getter Method
Syntax
get is a Method but It is called directly in the same method as property.
Example
Here,
We have used get accessor property method to show welcomeText
Setter Method
Syntax
get is a Method but It is called directly in the same method as property.
Example
Here,
We have used set accessor property method to change the Name of identity.
set method must have 1 parameter
Object.defineProperty()
By Using defineProperty we can define new properties and methods directly on the object with get and set Keywords.
Syntax
Here,
objectName is the Name of the Object.
methodName is the Name of the Method to create in the Object.
Example
Here,
You can see we have create 1 get and 1 set Method.
Here,
Browser will ask for Name in a Prompt Box and your name will be displayed in the Output.