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

JavaScript使用setter重置Circle默认坐标时y为undefined如何修复

错误原因
  • 核心问题是对JS属性访问器(getter/setter)的参数规则理解有误:set访问器本身只支持接收1个入参,这个入参就是赋值时等号右侧传入的完整值;get访问器不需要接收任何入参。你原有代码给setter写了(a, b)两个形参,执行circle.defaultLocation = {x:5, y:6}时,整个对象会被第一个形参a接收,第二个形参b没有传入值,默认为undefined,最终赋值生成的defaultLocation自然就是x: {x:5, y:6}, y: undefined,和你在控制台看到的结果完全一致。
  • 次要问题是冗余代码:你定义的getDefaultLocation方法、getter访问器都写了未被使用的a、b形参,不影响核心运行但属于无效代码。
修正方案

修正setter的参数逻辑,去掉无效的冗余形参即可,修正后可正常给defaultLocation赋值:

function Circle(radius) {
  this.radius = radius;
  
  // 私有默认坐标变量
  let defaultLocation = {
    x: 0,
    y: 0
  };

  this.getDefaultLocation = function() {
    return defaultLocation;
  };
  
  Object.defineProperty(this, 'defaultLocation', {
    // getter无入参,直接返回私有变量
    get: function() {
      return defaultLocation;
    },
    // setter仅接收1个入参,即赋值传入的完整对象
    set: function(newLocation) {
      // 可选增加入参合法性校验,避免传入非法值
      if (typeof newLocation !== 'object' || newLocation === null) {
        throw new Error('赋值必须是包含x、y坐标属性的对象');
      }
      defaultLocation = {
        x: newLocation.x,
        y: newLocation.y
      };
    }
  });
}

const circle = new Circle(10);
// 正常赋值
circle.defaultLocation = {
  x: 5,
  y: 6
};
// 打印验证:输出 {x: 5, y: 6},符合预期
console.log(circle.defaultLocation);

内容的提问来源于stack exchange,提问作者eric2022

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 13:33:23