Babel实现ES6继承解析(完美对Array实现继承)

前端之家收集整理的这篇文章主要介绍了Babel实现ES6继承解析(完美对Array实现继承)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
var _createClass = function () {
function defineProperties(target,props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target,descriptor.key,descriptor);
}
}

return function (Constructor,protoProps,staticProps) {
    if (protoProps) defineProperties(Constructor.prototype,protoProps);
    if (staticProps) defineProperties(Constructor,staticProps);
    return Constructor;
};

}();

function _classCallCheck(instance,Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}

function _possibleConstructorReturn(self,call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}

function _inherits(subClass,superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function,not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype,{
constructor: {
value: subClass,enumerable: false,writable: true,configurable: true
}
});
if (superClass) subClass.proto = superClass;
}

var FakeArray = function (_Array) {
// 设置 FakeArray.proto = Array.proto
// 设置 FakeArray.prototype = Array.prototype (用空对象中介)
_inherits(FakeArray,_Array);

function FakeArray(props) {
    _classCallCheck(this,FakeArray);//是否new操作

    //用<a href="/tag/fulei/" target="_blank" class="keywords">父类</a>构造<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>返回的对象作为基础
    var _this = _possibleConstructorReturn(this,(FakeArray.__proto__).call(this,props));

    //开始初始化
    _this.a1 = 111;
    return _this;
}

_createClass(FakeArray,[{
    key: "bark",value: function bark() {
        console.log(11);
    }
}]);

return FakeArray;

}(Array);

var a = new FakeArray(3);

console.log(a);

// 我之前用的继承方式

function Child(props) {
this.c1 = 'c111';
Parent.call(this,props);
}

function Parent() {

}

Parent.prototype.p1 = 'parent111';
let o = {};
o.proto = Parent.prototype;
o.constructor = Child;
Child.prototype = o;

let ret = new Child();

console.log(ret.c1,ret.p1);

猜你在找的程序笔记相关文章