new的过程发生了什么?
// 假设有一个构造函数Animal
function Animal() {
this.name = name;
}
const monkey = new Animal();
在这个过程中:
- 创建了一个空对象monkey
- 将新对象的_proto_指向构造函数Animal的prototype
- 将构造函数中的this绑定到新创建的对象上,执行构造函数中的代码
- 如果构造函数没有return或return的是基本数据类型,则返回这个新对象,否则返回引用类型的数据
假设有一个对象Person,怎么指定他的原型对象为Animal?
// 第一种方式
function Person() {
// this.cell = cell;
}
Person.prototype = monkey;
// 第二种方式 create方法第一个参数为新创建对象的原型对象
const Person = Object.create(monkey)