定义与区别
seal: 封闭。只允许操作入参对象原本就可写的属性
freeze: 冻结,不允许操作所有属性,包括原型与原型链
应用
React源码,开发模式下
初次渲染,ref会被赋值为一个具有current的seal对象,而props.children则是一个childArray的冻结对象
freeze usage
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
const childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
const childArray = Array(childrenLength);
for (let i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
if (__DEV__) {
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
ref usage
export function useRef<T>(initialValue: T): {current: T} {
currentlyRenderingFiber = resolveCurrentlyRenderingFiber();
workInProgressHook = createWorkInProgressHook();
let ref;
// 初次渲染,直接赋值为{current: initialValue},并使用seal封闭,并初始化workInProgressHook.memoizedState
if (workInProgressHook.memoizedState === null) {
ref = {current: initialValue};
if (__DEV__) {
Object.seal(ref);
}
workInProgressHook.memoizedState = ref;
}
// 组件更新
else {
ref = workInProgressHook.memoizedState;
}
return ref;
}