theydy / notebook

记录读书笔记 + 知识整理,vuepress 迁移中 https://theydy.github.io/notebook/
0 stars 0 forks source link

computed watch 实现上的区别? #24

Open theydy opened 3 years ago

theydy commented 3 years ago

在说明不同之前首先需要区分一下 computed 的两个 getter 函数。第一个 getter 就是通过 Object.defineProperty 设置的 getter 函数,我们暂且称呼为 自身 getter 函数吧,这是 computed watcher 独有的 getter 函数。第二个是 Watcher 类中保存的 getter 函数我们称只为 watcher getter 函数 ,这个函数就是在 option 中定义 computed 时写的那个函数,或者对于 watch 来说只是一个访问了一下监听属性的函数。

现在我们现在有如下两个概念:

所以 computed watch 的不同有如下三点:

  1. computedwatch 第一个不同是 computed 本身会经过 Object.defineProperty 设置 get / set 函数(在 defineComputed 函数中),这个自身 getter 函数做两件事
    • watcher.depend() :computed watcher 收集依赖
    • watcher.evaluate():返回 computed 的值
  2. 第二个不同就是 computed watcher 有自身的 dep,而 user watcher 没有。这个很好理解,computed 经过了 Object.defineProperty 设置 get ,当然应该有 dep 收集依赖了。
  3. 第三个不同是 computed watch 默认是 lazy 模式,new Watcher 时不会立即取值,而是在自身 getter 函数触发是才取,后续只有在 computed watcher 的依赖变化时,才会重新取值。而 user watcher 在初始化时就会执行一次 watcher getter 函数 ,访问监听的属性,触发监听属性的收集依赖过程。