请教好心人一个js语法问题。
大家好,请教一个JavaScript的语法问题。下面这些代码有点儿多,但是我怕说不明白问题,所以都贴出来了,麻烦好心人帮看看。
这是《WebGL入门指南》里面作者写的一个Sim框架的代码。
其中
Sim.Publisher.prototype.subscribe里面的这两行代码我感到迷惑:
var subscribers = this.messageTypes[message];
subscribers.push({ subscriber : subscriber, callback : callback });
既然后面用了push,是不是说明subscribers是个数组,但是如果这个方法被反复执行,那么前面的subscribers的内容岂不是被反复覆盖的,那数组里面是不是总是只有一个元素。这有什么意义?但是后面还有Sim.Publisher.prototype.findSubscriber这个方法,需要遍历subscribers,显然里面不应该是一个元素。蒙圈了,求好心人解惑。
程序代码:
Sim = {}; Sim.Publisher = function() { this.messageTypes = {}; } Sim.Publisher.prototype.subscribe = function(message, subscriber, callback) { var subscribers = this.messageTypes[message]; if (subscribers) { if (this.findSubscriber(subscribers, subscriber) != -1) return; } else { subscribers = []; this.messageTypes[message] = subscribers; } subscribers.push({ subscriber : subscriber, callback : callback }); } Sim.Publisher.prototype.unsubscribe = function(message, subscriber, callback) { if (subscriber) { var subscribers = this.messageTypes[message]; if (subscribers) { var i = this.findSubscriber(subscribers, subscriber, callback); if (i != -1) this.messageTypes[message].splice(i, 1); } } else delete this.messageTypes[message]; } Sim.Publisher.prototype.publish = function(message) { var subscribers = this.messageTypes[message]; if (subscribers) { for (var i = 0; i < subscribers.length; i++) { var args = []; for (var j = 0; j < arguments.length - 1; j++) args.push(arguments[j + 1]); subscribers[i].callback.apply(subscribers[i].subscriber, args); } } } Sim.Publisher.prototype.findSubscriber = function (subscribers, subscriber) { for (var i = 0; i < subscribers.length; i++) if (subscribers[i] == subscriber)return i; return -1; }