JavaScript构造函数中显式return对象会覆盖默认this实例,返回该对象;return基本类型或null/undefined则仍返回this。

在 JavaScript 构造函数中,如果显式 return 一个对象(包括数组、函数、正则、Date 等引用类型),那么 new 表达式的返回值就会是这个对象,而不是默认创建的 this 实例。这是构造函数中影响实例化结果的关键机制。
构造函数默认返回 this
不写 return 或只 return 基本类型(如 number、string、boolean、null、undefined)时,new 调用始终返回新创建的 this 对象:
function Person(name) {
this.name = name;
// 没有 return,或 return 123 / 'abc' / undefined
}
const p = new Person('Alice');
console.log(p.name); // 'Alice'
console.log(p instanceof Person); // true
显式 return 对象会覆盖 this
只要 return 的是对象(含函数、数组、内置对象实例等),new 就会放弃默认 this,直接返回该对象:
function Person(name) {
this.name = name;
return { age: 25 }; // 返回普通对象
}
const p = new Person('Alice');
console.log(p.age); // 25
console.log(p.name); // undefined
console.log(p instanceof Person); // false
常见易忽略的“对象”返回值
以下 return 表达式都会导致实例被替换,需特别注意:
立即学习“Java免费学习笔记(深入)”;
-
return []—— 返回空数组,不是 Person 实例 -
return /abc/—— 返回正则对象 -
return new Date()—— 返回 Date 实例 -
return function() {}—— 返回函数对象 -
return Object.create(null)—— 返回无原型的对象
return null 或 undefined 不影响 this
return null、undefined、0、false、'' 等原始值,等价于没写 return,仍返回 this:
function Person(name) {
this.name = name;
return null; // ✅ 不改变返回结果
}
console.log((new Person('Bob')).name); // 'Bob'


















