You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何程序化调用JavaScript对象的getter以适配Handlebars.js?

解决Handlebars无法访问FrameNode对象getter属性的问题

Handlebars默认仅会遍历对象的自有可枚举属性,你看到的带(...)的属性是挂载在原型链上的getter方法,直接传递原对象自然无法读取这些属性的值。以下是两种程序化调用这些getter并转换为Handlebars可处理对象的方案:

方案1:手动提取指定属性

如果你明确知道需要哪些属性,可以逐个调用getter生成普通对象:

// 假设frameNode是你的FrameNode实例
const handlebarsData = {
  id: frameNode.id,
  absoluteBoundingBox: frameNode.absoluteBoundingBox,
  absoluteRenderBounds: frameNode.absoluteRenderBounds,
  backgrounds: frameNode.backgrounds,
  cornerRadius: frameNode.cornerRadius,
  // 按需添加其他需要的属性
};

// 将handlebarsData传入Handlebars进行渲染

方案2:自动提取所有原型链上的getter属性

如果需要批量处理所有getter属性,可以通过遍历原型链识别并调用getter,把值收集到新对象中:

function extractAllGetterValues(obj) {
  // 先复制对象的自有属性
  const data = {...obj};
  let currentProto = Object.getPrototypeOf(obj);

  // 遍历原型链,直到null
  while (currentProto !== null) {
    Object.getOwnPropertyNames(currentProto).forEach(propName => {
      const propDesc = Object.getOwnPropertyDescriptor(currentProto, propName);
      // 仅处理未在data中存在的getter属性
      if (propDesc.get && !(propName in data)) {
        data[propName] = obj[propName]; // 调用getter获取值
      }
    });
    currentProto = Object.getPrototypeOf(currentProto);
  }
  return data;
}

// 使用示例
const handlebarsData = extractAllGetterValues(frameNode);
// 传入Handlebars渲染

注意事项

  • 部分getter可能存在副作用(比如触发计算或状态变更),调用前请确认属性的行为
  • 如果FrameNode对象存在循环引用(比如children包含父节点),需要在提取时添加循环检测,避免无限递归
  • 优先使用方案1,按需提取属性,能减少不必要的计算开销

内容的提问来源于stack exchange,提问作者Robert Hošták

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:10:14