对象原型

30 阅读1分钟

new的过程发生了什么?

// 假设有一个构造函数Animal
function Animal() {
    this.name = name;
}
const monkey = new Animal();

在这个过程中:

  1. 创建了一个空对象monkey
  2. 将新对象的_proto_指向构造函数Animal的prototype
  3. 将构造函数中的this绑定到新创建的对象上,执行构造函数中的代码
  4. 如果构造函数没有return或return的是基本数据类型,则返回这个新对象,否则返回引用类型的数据

假设有一个对象Person,怎么指定他的原型对象为Animal?

// 第一种方式
function Person() {
    // this.cell = cell;
}
Person.prototype = monkey;
// 第二种方式 create方法第一个参数为新创建对象的原型对象
const Person = Object.create(monkey)