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

JavaScript中对象内方法无法正常工作问题求助

问题分析与修复方案

嘿,这个问题我太熟了!你现在的核心问题是——你只是引用了函数本身,没有调用它!当你写person.retireAtAge的时候,JavaScript会直接把这个函数的定义文本输出,而不是执行它并返回计算后的退休年龄。

快速修复

只需要在方法名后面加上(),让JS执行这个函数:

<p id="demo"></p>
<script>
var person = new Object();
person.firstName= "John";
person.lastName= "Doe";
person.age=40;
person.retireAtAge= function (){
  return (this.age+25);
};
// 关键修改:给retireAtAge加上(),触发函数执行
document.getElementById("demo").innerHTML=person.firstName + " Retires at " + person.retireAtAge();
</script>

额外优化建议(可选)

你可以用更简洁的对象字面量语法创建对象,写法更直观,同时还能用ES6的方法简写:

<p id="demo"></p>
<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 40,
  // ES6方法简写,不用写function关键字
  retireAtAge() {
    return this.age + 25;
  }
};
// 用模板字符串拼接内容,可读性更好
document.getElementById("demo").innerHTML = `${person.firstName} Retires at ${person.retireAtAge()}`;
</script>

这样修改后,页面就能正常输出John Retires at 65啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:46:23