I'm working through The Principles of Object-Oriented Javascript and am confused with Zakas's use of a named key inside an array (as opposed to inside an object). See comment:
function EventTarget() {}
EventTarget.prototype = {
constructor: EventTarget,
addListener: function(type, listener) {
if (!this.hasOwnProperty("_listeners")) {
// Why isn't this: `this._listeners = {};`
this._listeners = [];
}
if (typeof this._listeners[type] === "undefined") {
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
// more stuff
}
var target = new EventTarget();
target.addListener("message", function(event) {
console.log("Message is " + event.data);
});
His code works fine (as it does if you substitute the array for an object literal), but my understanding has been that you should use an object if you want to access the contents by name. From the array article on w3schools:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Is there a good reason that Zakas used an array like this? Can you please explain it? Alternatively, is this something I should submit to the errata?
type
is integerObject.getOwnPropertyNames(this._listeners)
and thenObject.keys(this._listeners)
.this._listeners
should be an object, not an array.type
isn't an integer (and it seems pretty likely it won't be, much more likely to be a string like"click"
)."length"
fortype
. Then exciting things happen.Map
.