javascript getters and setters explained code example
Example 1: getters and setters javascript classes
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(newName) {
this._name = newName;
}
walk() {
console.log(this._name + ' is walking.');
}
}
let bob = new Person('Bob');
console.log(bob.name);
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);