inherits实现

inherits实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
if (typeof Object.create === 'function') {
// 1. 判断是否具备Object.create方法
// 2. 定义inherits方法
function inherits(ctor, superCtor) {
ctor.super = superCtor;
// 3. 设置“子类”构造函数原型对象
// Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
// 通过Object.create()方法设置“子类”构造函数原型对象的__proto__为“父类”构造函数原型
// 另外将“子类”构造函数原型对象的constructor设回为“子类”构造函数
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
} else {
// 4. 若不支持Obeject.create()方法
function inherits(ctor, superCtor) {
ctor.super = superCtor;
// 5. 创建一个临时空构造函数
var tempCtor = function() {};
// 6. 使“父类”构造函数prototype对象寄生到临时空构造函数
tempCtor.prototype = superCtor.prototype;
// 7. 使“子类”构造函数prototype对象为临时构造函数实例,
ctor.prototype = new tempCtor();
ctor.prototype.constructor = ctor;
}
}
你的支持将鼓励我继续创作!