目录

手写new

function People(name) {
	this.name = name
}
 
People.prototype.sayName = function() {
	console.log('My name is ' + this.name)
}
 
let p = new People('jirengu')
p.name
p.sayName()

当执行 new People 的时候发生了什么?

  1. 创建一个空对象,创建的对象的proto指向People函数的prototype
  2. 执行People函数,其中对this赋值就是对这个空对象赋值
  3. 如果函数里没有return或者return的是非引用类型(数字、字符串、布尔、undefined、null),那么返回刚刚创建的对象

模拟new

function People(name) {
  this.name = name
}
 
People.prototype.sayName = function() {
  console.log('My name is ' + this.name)
}
 
function new2(fn, ...args) {
  let o = Object.create(fn.prototype)
  fn.bind(o)(...args)
  return o
}
 
let p = new2(People, 'hunger')
p.name
p.sayName()

思考

写一个函数,判断一个变量是不是基本类型

const isBasic = a => a===null || a === undefined || !a instanceof a.constructor