new了个啥

60 阅读1分钟

我们写new一下看看

看个例子

function Test(age,name){
  this.name=name
  this.age=age
  }
let test=new Test(18,'xx')
console.log(test)

image.png

可以看到它绑定好了constructor

console.log(test.constructor===Test)//true

如果构造函数直接返回一个对象又如何

function Test(age,name){
  this.name=name
  this.age=age
  return{
    age:20
        }
    }
let test=new Test(18,'xx')
console.log(test)

image.png 就直接返回该对象

new做了什么事

1.创建了一个空对象

2.指定原型

3.绑定了this,this为当前实例对象

4.返回构造好的对象

写代码开始

function create(Con, ...args) {
  let obj = {}
  Object.setPrototypeOf(obj, Con.prototype)//指定好原型链
  let result = Con.apply(obj, args)//不仅仅是绑定this,执行函数
  // 如果构造函数直接返回,还是返回值;但是如果没有返回值就是undefined
  //console.log(result)
  //console.log(obj)
  //console.log(result instanceof Object)
  return result instanceof Object ? result : obj//有两种情况,一种返回对象,一种正常返回

}
function Test(name, age) {
  this.name = name;
  this.age = age;
  // return{
  //   age:18
  // }
}

Test.prototype.sayName = function () {
  console.log(this.name);
};

const a = create(Test, "xx", 25);
console.log(a.age);
a.sayName();

现在逐行分析

  • let obj={}//创建一个空对象
  • Object.setPrototypeOf(obj, Con.prototype)//指定好原型
  • let result = Con.apply(obj, args)//修改this为当前对象,并执行构造函数,如果没指定为返回值,result就是undefined,如果Test指定返回值就是返回值
  • return result instanceof Object ? result : obj//result是一个对象说明构造函数写死了返回值,如果不是就返回创建好的对象obj 借鉴这些文章juejin.cn/post/684490… juejin.cn/post/684490…