OO – Encapsulation Example
by Shane Porter
JavaScript
// Define the Person constructor
function Person(name) {
this.name = name;
};
// via closure
function StudentClosure(name, age) {
var _age = age;
Person.call(this, name);
// to be able to have protoype methods that can access _age,
// they have to be defined within the constructor's scope
this.setAge = function (age) {
_age = age;
};
this.getAge = function () {
return _age;
};
}
StudentClosure.prototype = Object.create(Person.prototype);
StudentClosure.prototype.constructor = StudentClosure;
// via IIFE
var StudentIIFE = (function () {
var _age;
// Define the Student constructor
function StudentIIFE(name, age) {
// Call the parent constructor function in own context
Person.call(this, name);
_age = age;
};
StudentIIFE.prototype = Object.create(Person.prototype);
StudentIIFE.prototype.constructor = StudentIIFE;
StudentIIFE.prototype.setAge = function (age) {
_age = age;
};
StudentIIFE.prototype.getAge = function () {
return _age;
};
return StudentIIFE;
}());
// Example usage:
var student1 = new StudentClosure("Janet", 24);
console.log('student1', student1);
student1.setAge(25);
console.log('student1.getAge()', student1.getAge());
var student2 = new StudentIIFE("Walter", 45);
console.log('student2', student2);
student2.setAge(46);
console.log('student2.getAge()', student2.getAge());