编程语言
首页 > 编程语言> > JavaScript类

JavaScript类

作者:互联网

https://zh.javascript.info/class-inheritance#homeobject
以下是babel编译过的继承,记录

"use strict";

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

function _setPrototypeOf(o, p) {
	_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
		o.__proto__ = p;
		return o;
	};
	return _setPrototypeOf(o, p);
}

function _createSuper(Derived) {
	var hasNativeReflectConstruct = _isNativeReflectConstruct();
	return function _createSuperInternal() {
		var Super = _getPrototypeOf(Derived),
		result;
		if (hasNativeReflectConstruct) {
			var NewTarget = _getPrototypeOf(this).constructor;
			result = Reflect.construct(Super, arguments, NewTarget);
		} else {
			result = Super.apply(this, arguments);
		}
		return _possibleConstructorReturn(this, result);
	};
}

function _possibleConstructorReturn(self, call) {
	if (call && (typeof call === "object" || typeof call === "function")) {
		return call;
	}
	return _assertThisInitialized(self);
}

function _assertThisInitialized(self) {
	if (self === void 0) {
		throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
	}
	return self;
}

function _isNativeReflectConstruct() {
	if (typeof Reflect === "undefined" || !Reflect.construct)
		return false;
	if (Reflect.construct.sham)
		return false;
	if (typeof Proxy === "function")
		return true;
	try {
		Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
		return true;
	} catch (e) {
		return false;
	}
}

function _getPrototypeOf(o) {
	_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
		return o.__proto__ || Object.getPrototypeOf(o);
	};
	return _getPrototypeOf(o);
}

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

let Animal = function Animal(name) {
	_classCallCheck(this, Animal);

	this.name = name;
};

let Rabbit = /*#__PURE__*/ function (_Animal) {
	_inherits(Rabbit, _Animal);

	var _super = _createSuper(Rabbit);

	function Rabbit(name) {
		var _this;

		_classCallCheck(this, Rabbit);

		_this = _super.call(this, name);
		_this.created = Date.now();
		return _this;
	}

	return Rabbit;
}
(Animal);

let rabbit = new Rabbit("White Rabbit"); // 现在好了

alert(rabbit.name); // White Rabbit

标签:function,return,JavaScript,getPrototypeOf,call,superClass,Rabbit
来源: https://blog.csdn.net/yangtao080304/article/details/117229705