- 执行 new 一个对象需要经过的过程
- 创建一个新的对象
- 将构造函数的作用域付给新对象
- 为该对象添加属性
- return 该对象
- 举例
// 构造函数写法
function Parent(name, age) {
this.name = name
this.age = age
}
Parent.prototype.say = function() {
console.log(this.name)
}
let child = new Parent('tutao', 25)
child.say() // tutao
// class写法
class Parent1 {
constructor(name, age) {
this.name = name
this.age = age
}
say() {
console.log(this.name)
}
}
let child1 = new Parent1('tutao', 25)
child1.say() // tutao
- 《javascript 模式》解释:当我们 new 一个构造器,主要有三步:
- 创建一个空对象, 将他的引用赋给 this,继承函数的原型
- 通过 this 将将属性和方法添加至这个对象
- 最后返回 this 指向的新对象,也就是实例
- 手动按照原理实现一个 new 方法
const myNew = function (Parent, ...prop) {
let child = {} // 创建一个空对象
child.__proto__ = Parent.prototype // 空对象的引用赋给this
Parent.apply(child, prop) // 属性和方法添加至新对象
return child // return 新对象
}
let child = myNew(Parent, 'tutao', 25)
child.say() // tutao