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?
The only reason I can see is : confusing people. JavaScript doesn't enforce anything, really, and since everything is an object, you can do pretty much whatever you want. This guy is using an array to store named properties, but he could very well have used a function or anything else !
Edit : almost everything is an object (it would have occured to me that someone could try to set a property on undefined
, since one of the most common errors in JavaScript is TypeError : undefined is not an object
. sighs JavaScript, why are you doing this to us ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With