构造函数中return基本类型被忽略,仍返回this;return引用类型则覆盖默认返回值,返回该对象;return this等效于不写return;class constructor禁止return引用类型,否则报错。

构造函数中使用 return 时,返回值是否生效,取决于返回的是基本类型还是引用类型——这是 JavaScript 中一个容易被忽略但很关键的规则。
返回基本类型(string、number、boolean、null、undefined、symbol、bigint)会被忽略
当构造函数显式 return 一个基本类型值时,JavaScript 会直接忽略该返回值,仍然返回新创建的实例对象(即 this)。
例如:
function Person(name) {
this.name = name;
return 'ignored';
}
const p = new Person('Alice');
console.log(p); // Person { name: 'Alice' }
console.log(p instanceof Person); // true
即使你 return 42、return null 或 return undefined,结果都一样:构造函数照常返回新对象。
返回引用类型(object、array、function、date、regex 等)会覆盖默认返回值
只要 return 的是对象(包括数组、函数、正则、Date 等),构造函数就会放弃原本要返回的 this,转而返回你指定的那个引用值。
例如:
function Person(name) {
this.name = name;
return { custom: true, message: 'Hello' };
}
const p = new Person('Bob');
console.log(p); // { custom: true, message: 'Hello' }
console.log(p instanceof Person); // false
此时 p 不再是 Person 实例,而是一个普通对象,原型链也断开了。
特殊情况:return this 显式返回实例,效果等同于不写 return
显式写 return this 是合法且常见的,它不会改变默认行为,仍返回新创建的实例。
- 这在链式调用或条件初始化中有时有用
- 如果构造函数内部有提前退出逻辑(如校验失败),也可以配合
return提前终止 - 但注意:提前
return基本类型仍无效;若想真正中断并返回空/错误,应抛出异常或改用工厂函数
实际建议与注意事项
- 除非有明确设计意图(比如实现“单例构造”或“代理返回”),否则避免在构造函数中
return引用类型,否则会破坏instanceof和原型继承 - 不要依赖
return undefined或return;来“修正”返回值——它们本来就不影响结果 - 若需要灵活控制返回内容(比如缓存实例、返回子类对象),更推荐使用工厂函数(普通函数 +
return)而非构造函数 - ES6 类(
class)语法中,constructor内部不允许return引用类型,否则会报错:TypeError: Derived constructors may only return object or undefined
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











