基于事件驱动,node 中自己实现了一个发布订阅
const EventEmitter = require("events");
const event = new EventEmitter();
console.log(event.__proto__);
实例的属性和方法(每个人都独有一份),原型上的属性和方法(所有人共享一个)
比如下面的 name 就是实例的属性,eat 就是原型上的方法
function Man(name) {
this.name = name;
}
Man.prototype.eat = function () {
console.log("我他喵吃吃吃");
};
new Man("kaimo");
new Man("kaimo313");
常用的继承策略:继承父类的原型链
function Man() {
}
let man = new Man();
console.log(man.__proto__ === Man.prototype); // true
console.log(Man.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__); // null 对象的原型的 __proto__ 指向的是 null
继承父类的原型方法:
1、Man.prototype.__proto__ = EventEmitter.prototype
const EventEmitter = require("events");
function Man() {
}
Man.prototype.__proto__ = EventEmitter.prototype; // 最早
let man = new Man();
console.log(man.on);
2、Man.prototype = Object.create(EventEmitter.prototype)
const EventEmitter = require("events");
function Man() {
}
Man.prototype = Object.create(EventEmitter.prototype); // es5 版本
let man = new Man();
console.log(man.on);
Object.create 方式的原理
function create(parentPrototype) {
function Fn() {
}
Fn.prototype = parentPrototype;
return new Fn();
}
3、Object.setPrototypeOf(Man.prototype, EventEmitter.prototype)
const EventEmitter = require("events");
function Man() {
}
Object.setPrototypeOf(Man.prototype, EventEmitter.prototype); // es6 版本
let man = new Man();
console.log(man.on);
4、extends 语法:class Man extends EventEmitter
原型链示意图:
使用 util 模块的 inherits 实现继承
const EventEmitter = require("events");
const util = require("util");
function Man() {
}
util.inherits(Man, EventEmitter);
let man = new Man();
console.log(man.on);
我们先在调用处打上断点,然后在左侧里找到 utils 下的 inherits 右键添加 inherits 到监视
然后单步调试,就能进入到 inherits 方法
我们可以看到 util.inherits
的底层实现就是使用了 Object.setPrototypeOf(ctor.prototype, superCtor.prototype)