美文网首页
面试官:了解new吗?在new的函数里return会发生什么?

面试官:了解new吗?在new的函数里return会发生什么?

作者: 超级码力 | 来源:发表于2021-03-04 11:46 被阅读0次

了解new吗?说一下new的原理

我 :创建一个空对象,然后对象的原型指向构造函数的prototype,然后通过call或者apply绑定this,然后return出去这个对象

紧接着面试官追问在new的函数里return会发生什么

我: 猝(原谅我很菜)

面试结束后我又仔细研究了一下new
之前的代码:

function _new(func,...arg){
  let obj = {}
  obj.__proto__ = func.prototype
  obj  = func.apply(obj,arg)
  return obj
}

但是如果简单试一下就知道

function person(age,name){
  this.age = age
  this.name = name
  return 111
}
console.log(_new(person,12,'asd'))  // 111
console.log(new person(12,'asd'))   // person { age: 12, name: 'asd' }

如果return null 自己写的_new也会返回null 而原生的却可以正常返回 但是如果我们返回的类型是对象呢 试一下

function person(age,name){
  this.age = age
  this.name = name
  return {}
}
console.log(_new(person,12,'asd'))  // {}
console.log(new person(12,'asd'))   // {}

数组也试一下

function person(age,name){
  this.age = age
  this.name = name
  return []
}
console.log(_new(person,12,'asd'))  // []
console.log(new person(12,'asd'))   // []

再试一下function

function person(age,name){
  this.age = age
  this.name = name
  return function a (){}
}
console.log(_new(person,12,'asd'))  // [Function: a]
console.log(new person(12,'asd'))   // [Function: a]

可以看出他们的共同点就是除了null 剩下的type of === 'object'或type of === 'function' 所以我们改造一下_new

function _new(func,...arg){
  let obj = {}
  obj.__proto__ = func.prototype
  let res = func.apply(obj,arg)
  console.log(typeof res)
  if (res !== null && (typeof res === 'object' || typeof res === 'function')) {
    return res
  }
  return obj
}

相关文章

网友评论

      本文标题:面试官:了解new吗?在new的函数里return会发生什么?

      本文链接:https://www.haomeiwen.com/subject/ptzhqltx.html