源码分析
/**
* 使一个类继承另一个类
* 该函数作用类似于node中的util.inherits
* @param subClass 子类
* @param superClass 超类
*/
function _inherits(subClass, superClass) {
// 检查超类必须是函数或者null,否则会出错
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
// 将超类的prototype作为子类的prototype.__proto__。这样生成的对象中,原型链上就包括超类的prototype了。
// 修改后:subClass.prototype.__proto===superClass.prototype
// 修改后:sub=new subClass();sub.__proto__.__proto__===superClass.prototype
subClass.prototype = Object.create(
superClass && superClass.prototype,
// 注意这里,重新赋子类的构造方法回子类的原型链上
// 因为一般对于一个构造函数A来说,A.prototype.constructor===A
{
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
// 修改子类的原型为超类。暂不知道这样做的目的是是什么,大概是因为要贴合标准吧。
// 修改后:subClass.__proto__===superClass
// 注意:在修改之前subClass.__proto__===Function.prototype,因为函数(类)实际上都是Function的实例
if (superClass)
Object.setPrototypeOf ?
Object.setPrototypeOf(subClass, superClass)
: subClass.__proto__ = superClass;
}
例子
var Animal = function () {
function Animal() {
_classCallCheck(this, Animal);
}
Animal.prototype.bite = function bite() {};
return Animal;
}();
var Person = function (_Animal) {
_inherits(Person, _Animal);
function Person(weight) {
_classCallCheck(this, Person);
return _possibleConstructorReturn(this, _Animal.call(this, weight));
}
Person.prototype.think = function think() {};
return Person;
}(Animal);
var tom = new Person();
其中_inherits的作用就是:使得Person.prototype.__proto__ === Animal.prototype
;或者说,tom.__proto__.__proto__ === Animal.prototype
0 条评论