Skip to content

Instantly share code, notes, and snippets.

@ptsurko
Last active December 20, 2015 08:09
Show Gist options
  • Save ptsurko/6098118 to your computer and use it in GitHub Desktop.
Save ptsurko/6098118 to your computer and use it in GitHub Desktop.
JavaScript - accessing private variables in prototype methods
var Animal = (function() {
var heartRate; //private variable available in prototype functions
function Animal() {
heartRate = 90;
console.log('heart rate: ' + heartRate);
};
Animal.prototype = {
constructor: Animal,
doDance: function() {
heartRate = 120;
console.log('heart rate: ' + heartRate);
}
}
return Animal;
})();
var Human = (function() {
var isArmRaise;
function Human() {
isArmRaise = false
Animal.prototype.constructor.call(this);//calling animal's constructor
console.log('is arm raised: ' + isArmRaise);
}
function F() { }
F.prototype = Animal.prototype;
Human.prototype = new F(); //To avoid calling animal's constructor
Human.prototype.constructor = Human;
Human.prototype.doDance = function() {
isArmRaise = true;
Animal.prototype.doDance.call(this);
console.log('is arm raised: ' + isArmRaise);
}
return Human;
})();
var h = new Human();
h.doDance();
var AnimalPrototype = (function () {
var heartRate; //private variable available in prototype functions
return {
constructor: function () {
heartRate = 90;
console.log('heart rate: ' + heartRate);
},
doDance: function () {
heartRate = 120;
console.log('heart rate: ' + heartRate);
}
}
})();
var HumanPrototype = (function () {
var isArmRaise;
var HumanPrototype = Object.create(AnimalPrototype)
HumanPrototype.superclass = AnimalPrototype;
HumanPrototype.constructor = function () {
isArmRaise = false;
HumanPrototype.superclass.constructor.call(this);
console.log('is arm raised: ' + isArmRaise);
}
HumanPrototype.doDance = function () {
isArmRaise = true;
HumanPrototype.superclass.doDance.call(this);
console.log('is arm raised: ' + isArmRaise);
}
return HumanPrototype;
})();
var h = Object.create(HumanPrototype);
h.constructor();
h.doDance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment