var publisher = function() { return { currentList: [], add: function(person) { this.currentList.push(person) }, publish: function() { let currentList = this.currentList for (let i = 0; i < currentList.length; i++) { // 遍历订阅者的数组 currentList[i].receiveText() } } } }
var subscriber = function(name) { return { name: name, receiveText: function() { console.log(`${this.name} has received the message`) } } }
var p1 = publisher() var jack = subscriber('jack') var Marry = subscriber('Marry') // 订阅公众号 p1.add(jack) p1.add(Marry) // 公众号发布推文 p1.publish() // jack has received the message // Marry has received the message
var publisher = function() { return { currentList: [], add: function(person) { this.currentList.push(person) }, publish: function() { let currentList = this.currentList for (let i = 0; i < currentList.length; i++) { currentList[i].receiveText() } }, remove: function(person) { let currentList = this.currentList for (let i = 0; i < currentList.length; i++) { if (currentList[i] === person) currentList.splice(i, 1) } } } }
var p1 = publisher() var jack = subscriber('jack') var Marry = subscriber('Marry') // 订阅公众号 p1.add(jack) p1.add(Marry) // 公众号发布推文 p1.publish() // jack has received the message // Marry has received the message p1.remove(jack)