构造函数中return对象会覆盖new默认返回的this实例,返回原始值则忽略return仍返回this;本质是new执行逻辑决定最终返回值优先级。

在 JavaScript 构造函数中,this 默认指向新创建的实例对象。但如果你在构造函数中显式使用 return 语句返回一个**已存在的对象(非原始值)**,那么 new 表达式的返回值会被这个对象覆盖,而不再是你原本的 this 实例。
构造函数中 return 对象会覆盖默认 this 绑定
当构造函数执行时:
- 如果 return 的是**对象类型(包括数组、函数、正则、Date、自定义对象等)**,new 调用的结果就是该返回值,与 this 无关;
- 如果 return 的是**原始值(undefined、null、字符串、数字、布尔、symbol、bigint)**,则 new 忽略该 return,仍返回 this 所指的新实例;
- 注意:return undefined 等价于不写 return,不会覆盖 this。
典型示例对比
✅ 返回对象 → 覆盖 this:
this.name = 'ignored';
return { name: name, say: () => 'Hi' };
}
const p = new Person('Alice');
console.log(p.name); // 'Alice'
console.log(p instanceof Person); // false
❌ 返回原始值 → this 依然生效:
function Person(name) {this.name = name;
return 'oops'; // 被忽略
}
const p = new Person('Bob');
console.log(p.name); // 'Bob'
console.log(p instanceof Person); // true
为什么能“覆盖” this?
本质不是 this 被修改,而是 new 的执行逻辑决定最终返回值:
- new 创建空对象并绑定到 this;
- 执行构造函数体;
- 检查 return 值:若为对象,直接返回它;否则返回 this。
所以这不是“覆盖 this”,而是 new 规则让 return 值优先级高于 this。
实际注意事项
- 这种写法会破坏 instanceof 和原型链关系,谨慎用于单例、缓存或代理场景;
- 箭头函数没有自己的 this,构造函数里用箭头函数定义方法时,其内部 this 不受 new 影响;
- TypeScript 中这类 return 可能触发类型警告,需显式标注返回类型。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











