new调用构造函数时,若return原始类型(string/number/boolean/null/undefined)则忽略并返回新实例;若return对象则替代返回。如return 42得实例,return {y:2}得该对象且instanceof原构造函数为false。
当构造函数被 new 调用时,它默认会返回新创建的实例对象。但如果你在函数体内写了 return,返回值类型会决定最终结果——关键就看它是不是“对象”(即引用类型)。
看返回值是否为原始类型
原始类型包括:string、number、boolean、null、undefined。只要 return 的是其中任意一个,new 就会忽略它,照常返回新实例。
-
return 42→ 返回新对象,不是数字 42 -
return "hello"→ 返回新对象,不是字符串 -
return null或return undefined→ 同样被忽略,仍返回实例
区分 new String("x") 和 "x"
看似都是字符串,但行为完全不同:
-
return "x"是原始字符串 → 被忽略 -
return new String("x")是 String 实例(对象)→ 替代新对象返回 - 同理:
new Number(5)、new Boolean(true)、Object(123)都算对象,会被采纳
快速验证返回值类型
可在构造函数中加一行判断,避免误判:
console.log(typeof res, res instanceof Object)- 原始值:typeof 是
"string"/"number"等,且instanceof Object === false - 对象值:typeof 通常是
"object"或"function",且instanceof Object === true(null是例外,但null本身不触发替换)
实例对比更直观
写两个构造函数,只差一个 return:
-
function A() { this.x = 1; return 99; } →
new A()得到{x: 1} -
function B() { this.x = 1; return {y: 2}; } →
new B()得到{y: 2},x丢失,instanceof B为false

















