构造函数返回值的3种情况

241 阅读1分钟

例子

const obj = {
    res: false
}

// 1.不写return
function Fn1() {
    this.res = true
}

// 2.返回基本数据类型或者this
function Fn2() {
    this.res = true
    return false  // return this
}

// 3.返回对象
function Fn3() {
    this.res = true
    return obj
}

const f1 = new Fn1()
const f2 = new Fn2()
const f3 = new Fn3()

console.log(f1, f2, f3)
// Fn1 { res: true } 
// Fn2 { res: true } 
// { res: false }

解析

  1. 如果没写return,则返回构造函数创建的实例对象
  2. 如果return的是基本数据类型或者this,仍是返回构造函数创建的实例对象
  3. 如果return的是对象,则返回该对象;原本指向实例对象的this会被无效化