原型链、class、new

2 阅读2分钟

new 的原理

正常使用 new 的代码:

function Person(name) {
  this.name = name;
}
Person.prototype.sayHi = function () {
  console.log('hi, ' + this.name);
};

const p = new Person('Lc');
p.sayHi();
p.name;

new Person('Lc') 的过程中,实际上就是四个步骤:

  1. 创建空对象
  2. 把这个对象的原型指向构造函数的 prototype
  3. 让 this 指向这个对象,执行构造函数
  4. 如果构造函数返回的是对象,则返回它;否则返回 obj

prototype vs __proto__

直接用表格进行对照:

是谁的属性指向什么
Person.prototype函数才有一个对象,用来当作实例的原型
p.__proto__对象才有指向创建它的构造函数的 prototype

关系大概如下图:

graph LR
A[Person 函数] --.prototype--> B[prototype 对象]
C[p 实例] --.__proto__--> B

原型链

当我们查询一个属性,比如 p.sayHi:

  1. p 自己是否有 sayHi?没有
  2. p.__proto__有没有?有则返回
  3. 还没有继续向上:Object.prototype
  4. 再往上没了,null,查找结束,undefined

这条链条就是原型链。

p.toString();              // 能用
p.hasOwnProperty('name');  // 能用
p.abc;                     // undefined

这里需要注意,hasOwnProperty 只看自己,不看原型链。

但是,可以通过 in 来遍历原型链:

'toString' in a

通过一个表格快速对比一下:

写法查哪里结果
a.hasOwnProperty('y')只查自身true(this.y = 1 加在实例上)
a.hasOwnProperty('toString')只查自身false(toString 在 Object.prototype 上,不是 a 自己的)
'y' in a自身 + 原型链true
'toString' in a自身 + 原型链true(顺着链找到 Object.prototype)

Class 是语法糖

class Person {
  constructor(name) {
    this.name = name;
  }
  sayHi() {
    console.log('hi, ' + this.name);
  }
}

这个和前面的函数版本其实没有什么区别,本质上是一样的,class 只是更好看的写法。

Class 和函数的区别:

构造函数class
调用可以不加 new不加 new 会报错
提升函数声明提升不会提升(TDZ)
方法在 prototype 上也在 prototype 上(不可枚举)
严格模式看上下文自动内部严格模式

extends 和 super

class Animal {
  constructor(name) { this.name = name; }
  speak() { return this.name + ' 叫了一声'; }
}
​
class Dog extends Animal {
  constructor(name) {
    super(name);        // ← 必须先调 super,才能用 this
  }
  speak() {
    return super.speak() + ',汪汪';   // ← 调父类的方法
  }
}

extends:

  1. 让 Dog.prototype.__proto__ = Animal.prototype(方法能继承)
  2. 让 Dog.__proto__ = Animal(静态方法能继承)

super(name) 就是 Animal.call(this, name),调用父类构造函数来初始化 this。

super() 之前不能用 this,因为 this 还没被创建。这是 extends 独有的限制。

手写 new

function myNew(Ctor, ...args) {
  const obj = Object.create(Ctor.prototype);
  const result = Ctor.apply(obj, args);
  return result !== null && typeof result === 'object' ? result : obj;
}

可以进行验证:

function Person(name) { this.name = name; }
Person.prototype.say = function () { return this.name; };

const p = myNew(Person, 'P);
p.say();
p instanceof Person; // true

instanceof 的原理

其实就是沿着 proto 网上找,看看能不能找到目标对象的原型链。

如果要自己实现,如下:

function myInstanceof(obj, Ctor) {
  let proto = Object.getPrototypeOf(obj);
  while (proto) {
    if (proto === Ctor.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
  return false;
}

这里需要注意,instanceof 判断的是原型链上有没有他,而不是是不是他 new 出来的。