原型链篇:new一个实例的过程

247 阅读1分钟

实现方法

function Create(Con, ...args) {
  // 1. 创建一个空对象
  // const obj = {}
  // 2. 通过对象的隐式原型 = 构造函数的显式原型达到一个继承
  // Object.setPrototypeOf(obj, Con.prototype) // 等价于obj.__proto__ = Con.prototype
  const obj = Object.create(Con.prototype) // 等价于上面两步
  // 3. 通过回调函数改变构造函数的this指向初始化对象私有属性
  const result = Con.apply(obj, args)
  // 4. 当回调函数return的值为引用类型时,则使用return返的数据,否则使用obj
  return result instanceof Object ? result : obj
}

function func(name, age) {
  this.name = name
  this.age = age
  // 默认return this
}

func.prototype.sell="yes"

const newFunc = Create(func, 'weili', '18')
console.log(newFunc)

输出结果:

image.png

延申知识点(改变return值)

1.当return 返回引用类型数据

function func(name, age) {
  this.name = name
  this.age = age
  return {}
}

输出结果:此时this被替换成返回值

image.png

2.当return 返回基础类型数据

function func(name, age) {
  this.name = name
  this.age = age
  return 1
}

输出结果:忽视返回数据

image.png