how to use setters and getters in js code example
Example 1: getters and setters javascript
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'
Example 2: setters and getter best example
class Test {
// private variables
private int age;
private String name;
// initialize age
public void setAge(int age) {
this.age = age;
}
// initialize name
public void setName(String name) {
this.name = name;
}
// access age
public int getAge() {
return this.age;
}
// access name
public String getName() {
return this.name;
}
}
class Main {
public static void main(String[] args) {
// create an object of Test
Test test = new Test();
// set value of private variables
test.setAge(24);
test.setName("Programiz");
// get value of private variables
System.out.println("Age: " + test.getAge());
System.out.println("Name: " + test.getName());
}
}