目标
实现两个小工具函数,来判断是否为 响应性 对象和 只读对象
it('isReactive', () => {
const original = { foo: 1 };
const observed = reactive(original);
expect(isReactive(observed)).toBe(true);
expect(isReactive(original)).toBe(false);
});
it('happy path', () => {
const original = { foo: 1, bar: { baz: 2 } };
const wrapped = readonly(original);
expect(isReadonly(wrapped)).toBe(true);
expect(isReadonly(original)).toBe(false);
});
实现
因为在 baseHandlers 的 createGetter 中是有 isReadonly 的入参,所以只要想办法触发 get 就能知道是不是 reactive / readonly
export enum ReactiveFlags {
IS_REACTIVE = '__v_isReactive',
IS_READONLY = '__v_isReadonly',
}
export function isReactive(value) {
return !!value[ReactiveFlags.IS_REACTIVE];
}
export function isReadonly(value) {
return !!value[ReactiveFlags.IS_READONLY];
}
import { ReactiveFlags } from './reactive';
function createGetter(isReadonly = false) {
return function get(target, key) {
if (key === ReactiveFlags.IS_REACTIVE) {
return !isReadonly;
} else if (key === ReactiveFlags.IS_READONLY) {
return isReadonly;
}
const res = Reflect.get(target, key);
if (!isReadonly) {
track(target, key);
}
return res;
};
}