← 中文资源

简体中文版本

defineProperty 访问器属性

用 Object.defineProperty 定义 getter 与 setter:写入时校验范围,读取时返回计算值,内部变量不出现在对象属性里,也不会被外部直接改写。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

balance: 25.5 | formatted: $25.50
rejected: balance must be a non-negative number
still: $25.50

实现说明

defineProperty 访问器属性以函数 createAccount为骨架。 RangeError 之前有一道守卫:坏状态在这里就停下,不会继续往下走。

使用要点

  • 每一步打印都带着自己的标签:balance:、rejected:、still:。

常见问题

遇到格式错误的数据会怎样?

守卫处(入口)会抛出 RangeError,非法状态到不了主逻辑。

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 createAccount。

签名一览:function createAccount(initial)

核心语句

throw new RangeError('balance must be a non-negative number');
return '$' + balance.toFixed(2);

代码示例

function createAccount(initial) {
  let balance = initial;
  const account = { id: 'acct-1' };

  Object.defineProperty(account, 'balance', {
    enumerable: true,
    get() {
      return balance;
    },
    set(value) {
      if (!Number.isFinite(value) || value < 0) {
        throw new RangeError('balance must be a non-negative number');
      }
      balance = value;
    },
  });

  Object.defineProperty(account, 'formatted', {
    get() {
      return '$' + balance.toFixed(2);
    },
  });

  return account;
}

const account = createAccount(10);
account.balance = 25.5;
console.log('balance:', account.balance, '| formatted:', account.formatted);

try {
  account.balance = -1;
} catch (error) {
  console.log('rejected:', error.message);
}
console.log('still:', account.formatted);