JavaScript类

2021/5/24 20:56:00

本文主要是介绍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


这篇关于JavaScript类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程