We can define object accessors by using getters and setters. In contrast to the latter, which is used to set a property in an object, the former is used to retrieve a property from an object. Let's talk about them using examples.
Getters\sExample
read also : getter and setter in java
In the example that follows, an object called "business" is created, and "Getter" is used to display a property called "company" in the output.
<html>
<body>
<script>
var business= {
Name: "pro",
Country : "nour",
Company : "google",
get comp() {
return this.company;
}
};
document.write(business.company);
</script>
</body>
</html>
output
google
Setters
Example
In the example that follows, a new object called "business" is created, and the value of the property "company" is changed from PayPal to SolarCity as displayed in the output.
<html>
<body>
<script>
var business = {
Name: "pro",
Country : "nour",
company : "google",
set comp(val) {
this.company = val;
}
};
business.comp = "SolarCity";
document.write(business.company);
</script>
</body>
</html>
output
SolarCity
Top comments (0)