场景import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { list: ["hello"],丝抽 }; observe(data); const updateComponent = () => { for (const item of data.list) { console.log(item); } }; new Watcher(updateComponent); 先可以一分钟思考下会输出什么。 ... ... 虽然 list 的茧响值是数组,但我们是应式对 data.list 进行整体赋值,所以依旧会触发 data.list 的系统 set ,触发 Watcher 进行重新执行,云服务器数组输出如下: 场景 2import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { list: ["hello"],丝抽 }; observe(data); const updateComponent = () => { for (const item of data.list) { console.log(item); } }; new Watcher(updateComponent); 先可以一分钟思考下会输出什么。 ... ... 这次是茧响调用 push 方法,但我们对 push 方法什么都没做,应式因此就不会触发 Watcher 了。系统 为了让 push 还有数组的数组其他方法也生效,我们需要去重写它们,源码下载丝抽通过 代理模式,茧响我们可以将数组的应式原方法先保存起来,然后执行,系统并且加上自己额外的数组操作。 / * not type checking this file because flow doesnt play well with * dynamically accessing methods on Array prototype */ / export function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true, }); } */ import { def } from "./util"; const arrayProto = Array.prototype; export const arrayMethods = Object.create(arrayProto); const methodsToPatch = [ "push", "pop", "shift", "unshift", "splice", "sort", "reverse", ]; / * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method const original = arrayProto[method]; def(arrayMethods, method, function mutator(...args) { const result = original.apply(this, args); /