定义新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
相关产品推荐
相关产品推荐

