xxxxxxxxxx
const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get getName() {
return this.firstName;
},
//accessor property(setter)
set setName(newName){
this.firstName = newName;
}
};
// accessing data property
console.log(student.firstName); // Monica
// accessing getter methods
console.log(student.getName); // Monica
// trying to access as a method
console.log(student.getName()); // error
// change(set) object property using a setter
student.changeName = 'Sarah';
console.log(student.firstName); // Sarah
xxxxxxxxxx
// although you can just grab a property directly like this
Car1.colour
// or modify it like this
Car1.colour = "red"
// on the other hand, getter methods look like this
get colour() { // doesn't need a parameter
return this.colour // optionally attach values or operations on to it
}
// and setter methods look like this
set colour(newColour) {
this.colour = newColour
}
//Benifits of getters and setters
// implement logic that uses private data in the class
// eg. I might want to blend it with the current car colour
// Encapsulation: allows you to control how the data is accessed or modified.
// especially if you are implementing other logic
// Readability: code is much clearer as it is now in a method
// Compatibility: Some APIs or libraries expect you to use getters/setters
xxxxxxxxxx
let obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length === 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
};
obj.log.push('d');
console.log(obj.latest); //output: 'd'
xxxxxxxxxx
class Person {
constructor(name) {
this.name = name;
}
// getter
get personName() {
return this.name;
}
// setter
set personName(x) {
this.name = x;
}
}
let person1 = new Person('Jack');
console.log(person1.name); // Jack
// changing the value of name property
person1.personName = 'Sarah';
console.log(person1.name); // Sarah
Get and set
In order to allow controlled access to properties from outside the class, getter and setter methods are used.
A getter method allows reading a property’s value.
A setter method allows modifying a property’s value.
It is a common convention to write the name of the corresponding member fields with the get or set command.
Example
Let’s write get and set methods for __username in our User class.
xxxxxxxxxx
class User:
def __init__(self, username=None): # defining initializer
self.__username = username
def setUsername(self, x):
self.__username = x
def getUsername(self):
return (self.__username)
Steve = User('steve1')
print('Before setting:', Steve.getUsername())
Steve.setUsername('steve2')
print('After setting:', Steve.getUsername())
xxxxxxxxxx
class P:
def __init__(self, x):
self.__x = x
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
xxxxxxxxxx
For IntelliJ IDEA TO generate getters and setters:
Refactor-->EncapsulatFields
OR
use Keyboard Shortcut: alt + insert
xxxxxxxxxx
1) Syntax reasons. It’s easier and faster to read code
created with accessor functions
2) Encapsulation. I can create safer code with accessor functions.