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

JS调用Square.call()后value.a输出undefined而非25的原因及解决方法

问题产生原因

核心是JavaScript函数返回值的规则没匹配对:

  • 你是通过Square.call({}, 5)直接调用函数,没有用new关键字,这种调用模式下,函数的返回值完全由内部return语句决定。
  • 代码里虽然给call绑定的空对象this设置了a属性(值为25),但函数最后显式return a,返回的是原始类型的数字5,所以变量value实际接收到的是数字5,不是你之前绑定属性的那个对象。
  • 原始类型数字本身没有自定义的a属性,访问value.a自然得到undefined。
正确调整方式

选任意一种符合业务逻辑的改法即可:

  • 方案1:删除返回原始值的语句,让函数默认隐式返回绑定的this对象
function Square(a) {
  this.a = a ** 2;
}
const value = Square.call({}, 5);
console.log(value.a); // 输出25
  • 方案2:修改return语句,显式返回绑定了属性的this对象
function Square(a) {
  this.a = a ** 2;
  return this;
}
const value = Square.call({}, 5);
console.log(value.a); // 输出25
  • 方案3:按照构造函数标准写法用new调用,这种场景下构造函数返回原始值的逻辑会被自动忽略,默认返回新创建的实例对象
function Square(a) {
  this.a = a ** 2;
  return a; // new调用时返回原始值不会生效,不影响结果
}
const value = new Square(5);
console.log(value.a); // 输出25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:54:31