how to write getters and setters in javascript code example
Example 1: javascript class getter setter
class Person {
constructor(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
get fullName() {
return `Hello ${this.firstname} ${this.lastname}`;
}
set fullName(space) {
const parts = space.split(' ');
this.firstname = parts[0];
this.lastname = parts[1];
}
}
let run = document.getElementById("run");
run.addEventListener('click', () => {
let john = new Person('John', 'Connor');
console.log(john.fullName);
john.fullName = 'Billy Butcher';
console.log(john.firstname + ' ' + john.lastname);
})
Example 2: 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);
Example 3: getter and setters in js
var person={firstname:"chetha",secondname="kumar",get fullname()
{
return this.firstname+" "+this.secondname;
}
document.write(person.fullname);
var person={firstname:"chethan",secondname="kumar",course:"",set course(x)
{
this.course=x;
}
person.course="bca";
document.write(person.course);