我正在研究
The Principles of Object-Oriented Javascript并且与Zakas在数组中使用命名键(而不是在对象内部)相混淆.见评论:
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); });
他的代码工作得很好(如果你用数组替换对象文字就行了),但我的理解是,如果你想按名称访问内容,你应该使用一个对象.从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.
Zakas是否有充分理由使用这样的阵列?你能解释一下吗?或者,这是我应该提交给the errata的吗?