343 字
2 分钟
构造函数的返回值

构造函数的返回值#

在使用new 操作符去执行构造函数的时候,构造函数的返回值会决定了最终构建出来的实例是长什么样子的

例如以下例子

function Person(){
this.name = 'weng';
}
const per1 = new Person();
console.log(per1);

一般情况下构造函数是不需要返回值的,默认是返回this,内部的这些行为都会指定到this

但是有些面试题就要你整活,所以还是了解以下返回值对初始化后的实例的影响吧

// return; // 返回 this
// return null; // 返回 this
// return this; // 返回 this
// return false; // 返回 this
// return 'hello world'; // 返回 this
// return 2; // 返回 this
// return {}; // 返回 新建的 {}, person.name = undefined
// return []; // 返回 新建的 [], person.name = undefined
// return function(){}; // 返回 新建的 function,抛弃 this, person.name = undefined
// return new Boolean(false); // 返回 新建的 boolean,抛弃 this, person.name = undefined
// return new String('hello world'); // 返回 新建的 string,抛弃 this, person.name = undefined
// return new Number(32); // 返回 新的 number,抛弃 this, person.name = undefined

总结一下,构造函数中直接 return 一个非引用类型值或者null,会直接返回this对象;如果返回一个复杂对象或是 new 关键字初始化的对象,会直接返回此对象,也就是引用类型值。

构造函数的返回值
https://nollieleo.github.io/posts/构造函数的返回值/
作者
翁先森
发布于
2021-06-01
许可协议
CC BY-NC-SA 4.0