例子
先上个代码栗子
转换前
class Animal{
constructor(weight){
this.weight=weight;
}
bite(){}
}
class Person extends Animal{
constructor(weight,phone){
super(weight);
this.phone=phone;
}
think(){}
}
let tom=new Person();
转换后
var Animal = function () {
function Animal(weight) {
_classCallCheck(this, Animal);
this.weight = weight;
}
Animal.prototype.bite = function bite() {};
return Animal;
}();
var Person = function (_Animal) {
_inherits(Person, _Animal);
function Person(weight, phone) {
_classCallCheck(this, Person);
var _this = _possibleConstructorReturn(this, _Animal.call(this, weight));
_this.phone = phone;
return _this;
}
Person.prototype.think = function think() {};
return Person;
}(Animal);
var tom = new Person();
分析
类的继承主要是两个方面
1.原型链
首先要明确的是,类中定义的非静态方法实际上是定义在类的prototype上的。
创建的对象的原型链上应该包含超类的prototype。例子中这项工作是由这一句_inherits(Person, _Animal);
完成的。详情见 babel实现分析——辅助函数——_inherits
2.在子类构造函数中调用超类构造函数
也就是超类构造函数中对this做的操作,现在要作用在子类构造函数的this上。在ES6中这项工作是由super完成的。在上面的例子中,super要做的工作由这一句var _this = _possibleConstructorReturn(this, _Animal.call(this, weight));
完成。详情见 babel实现分析——辅助函数——_possibleConstructorReturn
0 条评论