encapsulation2
the most proper way (by returning)
by aninaslyan
JavaScript
let person = (function () {
var fullName = "Jason Shapiro";
var reg = new RegExp(/\d+/);
return {
setFullName : function (newValue) {
if( reg.test(newValue) ) {
console.log("invalid name");
}
else {
fullName = newValue; // Legal! The object has access to "fullName"
}
},
getFullName : function () {
return fullName; // Legal! The object has access to "fullName"
}
}; // End of the Object
}());
console.log(person.getFullName()); // Jason Shapiro
person.setFullName( "Jim White" );
console.log(person.getFullName()); // Jim White
person.setFullName( 42 ); // Invalid Name; the name is not changed.
person.fullName = 42; // Doesn't affect the private fullName variable.
console.log(person.getFullName()); // Jim White is printed again.