How to Design XML Documents
Aug 27 2:51:29
Back online!
Jul 30 16:17:53
Response to "Knowledge Management 2.0"
Jul 18 2:45:52
Drupal Apps
Jun 3 7:17:00
Google Sites and the AJAX universe
May 21 1:18:39
A number of people have described methods for private variables and methods within JavaScript.
In that spirit, this is another possible template. The main difference between this version and most others is that it uses the concise JSON notation for variable and method declarations.
File.Writer = File.Writer || function (filename, append, binaryMode) {
//:: private variables
with({
binaryMode: binaryMode || false,
handle: (function () {
if (binaryMode) { return new IO.FileOutputStream(filename, append) }
else { return new IO.FileWriter(filename, append); }
})()
}) {
//:: private methods
with({
}) {
//:: public methods and functions
var construct = {
write: function (data) {
handle.write(data, 0, (data.length || 32767));
},
close: function () {
handle.close();
}
}
}
//:: object initialiser
} return construct;
}
The usage of this object is then simply:
// returns a new instance of the File.Writer class
var x = File.Writer("\temp\test.txt", true);
x.handle(); // ERROR! returns "cannot find function"
x.write("Hello world");
x.close();
The chief drawback is that because JSON notation can only return Objects and not Functions, .prototype-style inheritance isn't possible. But it's a neat way to handle objects, and particularly singleton instances.