let a = { name: 'a', sendLetter: function(target) { target.receiveLetter(this) } }
let b = { name: 'b', receiveLetter: function(from) { console.log(`${this.name} have received the letter from ${from.name}`) } }
//无代理情况 a.sendLetter(b) // b have received the letter from a
//有代理情况
let proxy = { // 代理对象 name: 'proxy', sendLetter: function() { b.receiveLetter(this) }, receiveLetter: function(from) { console.log(`proxy have received the letter from ${from.name}`) this.sendLetter() } }
a.sendLetter(proxy) //proxy have received the letter from a //b have received the letter from proxy
let proxy = { // 代理对象 name: 'proxy', sendLetter: function() { b.receiveLetter(this) }, receiveLetter: function(from, letter) { console.log(`proxy have received the letter from ${from.name}`) if (letter.length > 200) { // 对收信方的"保护" console.log(`the letter from ${from.name} is too long`) console.log(`proxy have thrown the letter from ${from.name}`) return } this.sendLetter() } }
// 使用带length属性的对象来模仿letter a.sendLetter(proxy, { length: 100 }) // proxy have received the letter from a // b have received the letter from proxy
a.sendLetter(proxy, { length: 300 }) // proxy have received the letter from a // the letter from a is too long // proxy have thrown the letter from a
let b = { name: 'b', currentMood: function() { // 模拟b的情绪变化 if (Math.random() > 0.5) return'mad' return'happy' }, receiveLetter: function(from) { console.log(`${this.name} have received the letter from ${from.name}`) } }
let proxy = { // 代理对象 name: 'proxy', sendLetter: function() { b.receiveLetter(this) }, receiveLetter: function(from) { console.log(`proxy have received the letter from ${from.name}`) this.listenMood() }, listenMood: function() { // 监听b的心情 if (b.currentMood() === 'mad') { console.log('b is at mad now') console.log('proxy will send letter after one second') setTimeout(() => { this.listenMood() }, 1000) return; } this.sendLetter() } }