源码分析
/**
* 用于检查构造函数中super()是否被正确调用,然后产生构造函数的返回值
* 它(与传到call参数上的超类构造函数调用)完成了构造函数的super功能
* @param self 通常传入子类构造函数的this
* @param call 通常传入一个超类构造函数在子类this上的调用结果
*/
function _possibleConstructorReturn(self, call) {
// 检查子类的this是否存在
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
// 检查超类构造函数在子类this上的调用结果是否是类假值\object\function,如果是则返回这个值,如果不是则返回原来子类的this
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
例子
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();
其中_possibleConstructorReturn所在的那一行完成了ES6中的super()功能。即super(weight);
1 条评论
Jerold · 2021年1月18日 上午6:09
This website certainly has all of the information I needed concerning this subject and
didn’t know who to ask.