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

定义新User实例后调用incrementAge函数返回undefined/NaN问题排查

问题原因与修复方案

问题出在箭头函数的this指向特性上:

  • 箭头函数没有独立的this上下文,它的this会继承自定义时的外层作用域,而非调用它的对象实例。
  • 这里User.prototype.incrementAge用箭头函数定义,调用mike.incrementAge()时,this指向的是全局对象(浏览器环境为window,Node.js环境为global),而非mike实例。全局对象上不存在age属性,所以this.age是undefined,执行undefined++就会得到NaN。

修复方法很简单,把箭头函数改成普通函数即可:

function User(name, age) {
  this.name = name;
  this.age = age;
}

// 替换箭头函数为普通函数
User.prototype.incrementAge = function() {
  return this.age++;
}

const mike = new User("Mike", 20);
console.log(mike.incrementAge()); // 输出20,之后mike.age变为21

注:当前代码逻辑是先返回原年龄再自增,若需要先自增再返回,可改为return ++this.age。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:21:25