例子
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 }
解析
- 如果没写return,则返回构造函数创建的实例对象
- 如果return的是基本数据类型或者this,仍是返回构造函数创建的实例对象
- 如果return的是对象,则返回该对象;原本指向实例对象的this会被无效化