Although often we are used to seeing objects with public properties without any access control, JavaScript allows us to accurately describe properties. In fact, we can use descriptors in order to control how a property can be accessed and which logic we can apply to it. Consider the following example:
var personemployee = {
namefirst: "John""Boris",
surnamelast: "Smith""Sergeev",
get fullName() {
return this.namefirst + " " + this.surname;last;
},
set fullName(value) {
var parts = value.toString().split(" ");
this.namefirst = parts[0] || "";
this.surnamelast = parts[1] || "";
},
email: "john"boris.smith@packtpubsergeev@example.com"
};
The final result:
console.log(personemployee.fullName); //JohnBoris SmithSergeev
personemployee.fullName = "Mario"Alex Rossi";Makarenko";
console.log(personemployee.namefirst);//MarioAlex
console.log(personemployee.surnamelast);//RossiMakarenko
console.log(personemployee.fullName);//MarioAlex RossiMakarenko