实现 effect 返回 runner 功能

调用 effect 会返回一个函数 runner, 调用 runner 会再次执行 fn,调用 fn, fn 会返回一个返回值

先写一个单测

1
2
3
4
5
6
7
8
9
10
11
12
13
//reactivity/__test__/effect.spec.ts
...
it('should return renner when call effect', () => {
let foo = 10
const runner = effect(() => {
foo++
return 'foo'
})
expect(foo).toBe(11)
const r = runner()
expect(foo).toBe(12)
expect(r).toBe('foo')
})

实现单测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//reactivity/effect.ts
...
class ReactiveEffect {
private _fn: any //私有变量
constructor(fn) {
this._fn = fn
}
run() {
activeEffect = this
return this._fn() //新增返回fn的值
}
}
const effect = fn => {
const _effect = new ReactiveEffect(fn)
_effect.run()
return _effect.run.bind(_effect) //新增修改this指针
}