You can do nothing else but "prototypal OO style", as the languages you are
dealing with here are OOPLs that use only prototype-based inheritance so
far. You could simulate class-based inheritance, but I would consider that
misuse of the language.
http://javascript.crockford.com/javascript.html
Not at all, see above.
OH.. and perhaps I should have explained how I have it now. I decided
to make it a singleton.
Singleton is a concept for class-based OOP. IOW, you don't have a singleton
yet and you can't have one.
[...]
KeyListener.SECTION_1 = 77
KeyListener.SECTION_2 = 88
That is a possibility, although it might be a good idea to make those
prototype properties as well, see below.
function KeyListener()
{
throw new Error('must be used as a singleton');
Exception handling (try..catch..finally, throw) unfortunately is not
universally supported in ECMAScript implementations. I suggest you write a
wrapper that uses a string argument to eval() to execute code that uses
newer keywords (the string somewhat hides the code from non-compliant
parsers), and try to implement a fallback with window.onerror.
See
http://PointedEars.de/es-matrix for a list containing information about
which language feature is supported in which version of some common
implementations. The list is currently not exhaustive and is continuously
updated.
In this case, you will have to define a property of the created object that
tells whether something went wrong on construction. But as I said, the
concept of singleton is not applicable here.
}
KeyListener.listen = function (elm,scope) {
....
}
Probably not. If your goal is code reuse, then you would define the
listen() method as a prototype method, so that objects using KeyListener()
as their constructor would inherit it through the prototype chain:
KeyListener.prototype.listen = function(elm, scope)
{
// ....
};
KeyListener.stopListening (elm) {
...
}
KeyListener.setFocus() {
}
I'm afraid these are plain syntax errors, as your favorite error console
should have displayed (for debugging, I prefer Firebug for Firefox and MS
Script Debugger for IE).
I prefer to define prototype objects as follows:
KeyListener.prototype = {
constructor: KeyListener,
listen: function(...)
{
...
},
stopListening: function(elm)
{
...
},
setFocus: function()
{
...
}
};
See also the ECMAScript Support Matrix (URI above) for details about the
compatibility of object literals.
PointedEars