副作用函数:相对于纯函数而言,函数执行后对其他地方产生了影响
// 副作用函数effect中,读取了一个变量,在这个变量改变时,需要重新执行副作用函数
const data = { text: 'hello' }
const bucket = new Set()
const obj2 = new Proxy(data, {
get(target, key) {
bucket.add(effect)
return target[key]
},
set(target, key, val) {
target[key] = val
bucket.forEach(c => c())
return true
}
})
function effect() {
document.body.appendChild(document.createTextNode(obj2.text))
}
effect()
setTimeout(() => {
obj2.text = 'changed text'
}, 1000)
console.log('问题: 副作用函数写死,不灵活');