This presentation forms part of a tutorial on learning Javascript foundations. It introduces the Function module - a pattern for creating objects with private members.
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Javascript foundations: Function modules
1. function modules
Learning Javascript foundations
John Hunter
Nov 2008
1
2. Review - object module
var radio = {
volume: 0,
frequency: 88.0,
changeVolume: function (direction) {
if (direction === 'up') this.volume += 1;
else this.volume -= 1;
},
changeTuner: function (direction) {
if (direction === 'up') this.frequency += 4;
else this.frequency -= 4;
}
};
2
3. Good OO languages should support
encapsulation - objects should be able to
keep some properties private.
We cannot create private properties in
Javascript objects.
But there are ways to achieve the same effect.
3
4. function something () {
var secretTreasure = '$$$';
}
var myTreasure = something();
console.log(myTreasure);
>>> undefined
how can we get the secretTreasure ?
4
5. function functionName (arguments) {
var localVariable;
scope
return returnValue;
}
arguments, local variables and return
values are all in the function scope
5
6. function something () {
var secretTreasure = '$$$';
var notSoSecretTreasure = secretTreasure;
return notSoSecretTreasure;
}
var myTreasure = something();
console.log(myTreasure); >>> $$$
we can get the secretTreasure ?
6
7. function someFunction (arguments) {
var localVariable;
scope
closeure
return returnValue;
}
returned value has access to
var result = someFunction(); the function scope - even when
the function has completed!
7
8. function something () {
secretTreasure is private
var secretTreasure = '$$$';
return {
getTreasureLength: function () {
returned object shares scope
return secretTreasure.length;
with local variables
},
doubleTheTreasure: function () {
secretTreasure += secretTreasure;
}
};
}
var mine = something();
console.log(mine.getTreasureLength()); >>> 3
mine.doubleTheTreasure();
>>> 6
console.log(mine.getTreasureLength());
we can interact with private variables using public methods
8
9. Review
object properties are public
function local variables are private
function closures provide access to local variables after
the function has executed
functions can provide modules with private data
9