小问题

159 阅读1分钟

1、new 一个构造函数,如果函数返回 return {} 、 return null , return 1 , return true 会发生什么情况

function Foo(name) {
    this.name = name;
    return name
}
console.log(new Foo('猪头'))

function Bar(name) {
    this.name = name;
    return ['猪','头']
}
console.log(new Bar('猪头'))

function Empty(name) {
    this.name = name;
}
console.log(new Empty('猪头'))

// Foo {name: '猪头'}
// ['猪', '头']
// Empty {name: '猪头'}

console.log(Foo('猪头'))
console.log(Bar('猪头'))
console.log(Empty('猪头'))
// 猪头
// ['猪', '头']
// undefined

原因:构造函数作为普通函数的时候,它的return值是正常可控的。当作为构造函数执行的时候,new的操作符在执行代码时,会执行构造函数并apply它的this指向,new执行返回时会判断构造函数的返回值存在且是个对象,那么直接返回,否则返回new函数中申明的对象。

// 简版new
const myNew = function(C,...args) {
  const obj = Object.create(C.prototype);
  const returnVal = C.apply(obj,args)
  return (typeof returnVal === 'object') && !!returnVal ? returnVal : obj;
}