// 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());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.