关于new

12 阅读1分钟

什么是new

new是js的一个关键字,用于创建一个用户定义的对象类型或内置对象类型的实例。

  1. 基本语法
// 构造函数
function Person(name, age) {
  this.name = name
  this.age = age
}

// 使用 new 创建实例
const person1 = new Person('Alice', 25)
console.log(person1.name) // 'Alice'
console.log(person1.age) // 25

new做了什么

  1. 创建一个空对象
  2. 链接prototype
  3. 绑定this
  4. 返回对象

手写

function myNew(constructor, ...arg) {
  let newObj = {} // 创建空对象
  Object.setPrototypeOf(newObj, constructor.protoType) // 链接prototype
  const result = constructor.apply(newObj, arg) // 绑定this
  return result instanceof Object ? result : newObj // 返回对象
}