To make a property private, just make it local to the constructor. Any outside code trying to access
age
variable will result in an undefined
. But the outside code can still call the property that accesses this private variable using the public function getAge
.
function Person(name) {
// Define a variable only accessible inside of the Person constructor
var age = 25;
this.name = name;
this.getAge = function() {
return age;
};
this.growOlder = function() {
age++;
};
}
var person = new Person("Nicholas");
console.log(person.name); // "Nicholas"
console.log(person.getAge()); // 25
person.age = 100;
console.log(person.getAge()); // 25
person.growOlder();
console.log(person.getAge()); // 26
0 comments:
Post a Comment