Last active
December 20, 2015 08:09
-
-
Save ptsurko/6098118 to your computer and use it in GitHub Desktop.
JavaScript - accessing private variables in prototype methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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