0
What are the set and get property in class of JS?
What are the set and get property in class of JS?
const student = {
firstName: 'Ravi vishwakarma',
// accessor property(getter)
get getName() {
return this.firstName;
}
};
console.log(student.firstName); // Ravi vishwakarma
console.log(student.getName); // Ravi vishwakarma
console.log(student.getName()); // error
const student = {
firstName: 'Ravi vishwakarma',
//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};
console.log(student.firstName); // Ravi vishwakarma
// change(set) object property using a setter
student.changeName = 'Water fall';
console.log(student.firstName); // Water fall
const student = {
firstName: 'Ravi vishwakarma'
}
// getting property
Object.defineProperty(student, 'getName', {
get : function () {
return this.firstName;
}
});
// setting property
Object.defineProperty(student, 'changeName', {
set : function (value) {
this.firstName = value;
}
});
console.log(student.firstName); // Ravi vishwakarma
// changing the property value
student.changeName = 'Water fall';
console.log(student.firstName); // Water fall