[Javascript] Proxy - Snippets

Blog: https://dev.to/marclipovsky/discovering-the-power-of-javascript-proxy-after-all-this-time-4627

 

Lazy loading:

const lazyLoadHandler = {
  get: function (target, property) {
    if (!target[property]) {
      target[property] = expensiveComputation();
    }
    return target[property];
  },
};

const lazyLoadedObject = new Proxy({}, lazyLoadHandler);
const result = lazyLoadedObject.expensiveProperty; // Calls expensiveComputation() on first access

 

Readonly:

const readOnlyHandler = {
  set: function (target, property, value) {
    if (property === 'readOnly') {
      throw new Error('Cannot modify read-only property');
    }
    target[property] = value;
    return true;
  },
};

const protectedObject = new Proxy({ readOnly: true }, readOnlyHandler);
protectedObject.newProperty = 'some value'; // OK
protectedObject.readOnly = false; // Throws Error

 

posted @   Zhentiw  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-05-04 [React] Optimization Cookbook
2020-05-04 [Node] Prepare a package to be published to npm
2020-05-04 [React Testing] Test your Custom Hook Module with react-hooks-testing-library
2020-05-04 [React Testing] Test React Portals with within from React Testing Library
2020-05-04 [React Testing] Write React Application Integration Tests with React Testing Library
2020-05-04 [React Testing] Test timer related feature in React
2020-05-04 [React Testing] Test a Custom React Hook with renderHook from React Hooks Testing Library
点击右上角即可分享
微信分享提示