Files
knowledge-kit/Chapter2 - Web FrontEnd/2.44.md
2024-02-06 00:30:11 +08:00

54 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Vue 核心原理探究
## 一、动手做一个超简易 Vue
先简单分析下 Vue 做了什么,巴拉巴拉,好多功能。就说一个最基础的,数据改变了页面就改变。如何实现?
1. `Object.defineProperty` 提供的 getter、setter 便可以拦截到所有 getter 的使用方,做到依赖收集
2. 依赖收集getter 方法内部可以知道谁在调用此时可以做依赖收集。因为可能某个使用的方法getFullName会被调用多次所以需要用 set 去收集,保持唯一。且给 window 对象上挂载一个内部属性的方式,来记录谁去调用过 getter。收集后立马清空 window 对象的私有属性值
3. 派发执行:当数据改变的时候,也就触发到 setter此时 setter 内部将该属性收集到的依赖方全部调用一遍方法。
```js
/**
* 观察数据对象,数据驱动
*
* @param {any} obj
*/
function observe(obj) {
for (const key in obj) {
let getFunctionCallers = new Set();
let internalValue = obj[key];
Object.defineProperty(obj, key, {
set: function (newValue) {
internalValue = newValue;
// set 完立即调用所有依赖 getter 的方法
for (const getCaller of getFunctionCallers) {
getCaller();
}
},
get: function () {
// 依赖收集
if (window.__internalGetFunction) {
getFunctionCallers.add(window.__internalGetFunction);
}
return internalValue;
}
})
}
}
/**
* 用于依赖收集,将原始方法绑定到 window 的私有属性上
*
* @param {any} originalFunction
*/
function getFunctionProxy (originalFunction) {
window.__internalGetFunction = originalFunction;
originalFunction();
window.__internalGetFunction = null;
}
```