无constructor的class类还能new吗问题解析
作者:一溪之石
前言
某一天晚上跟"混子瑶"聊天,下面模拟一下对话情景。
我:混子瑶,今天学了什么啊?
混子瑶:今天学习了TypeScript
的class
类高级类型啊!(然后发了一张截图...,图上有明显的两个类 )
class Point { x: number; y: number }; class Point2D ( x: number; y: number }; const p: Point = new Point2D();
我:Point2D
都没有constructor
,它能被new
吗?
混子瑶:可以啊,你看它又没报错:
我:这么神奇的嘛?
混子瑶: emmmm...
果真是这么神奇的嘛?来试一下不就知道咯!
class语法糖
class
是ES6
提供的一个语法糖,本质是一个函数,它具有constructor
,static
默认方法... 咦?既然constructor
是class
类默认的,那岂不是显示,隐式都会默认去调用吗?文章的标题不就是一个子虚乌有的吗? 我们上babel来进行一下语法降级。
class A { x = 1; y = 2 } const a = new A(10,20) console.log(a); // {x: 1, y: 2} class B { constructor(x, y){ this.x = x; this.y = y; } x = 1; y = 2; } const b = new B(30,40) console.log(b); // {x: 30, y: 40} // 降级之后的代码 "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } 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, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var A = /*#__PURE__*/_createClass(function A() { _classCallCheck(this, A); _defineProperty(this, "x", 1); _defineProperty(this, "y", 2); }); var a = new A(10, 20); console.log(a); // {x: 1, y: 2} var B = /*#__PURE__*/_createClass(function B(x, y) { _classCallCheck(this, B); _defineProperty(this, "x", 1); _defineProperty(this, "y", 2); this.x = x; this.y = y; }); var b = new B(30, 40); console.log(b); // {x: 30, y: 40}
利用babel
降级把ES6
转化成了ES5
代码,更能证明class只是一个语法糖,本质只是一个函数。那我们来研究一下这些函数吧!🔥🔥🔥🔥
var B = /*#__PURE__*/ _createClass(function B(x, y) { _classCallCheck(this, B) _defineProperty(this, 'x', 1) _defineProperty(this, 'y', 2) this.x = x // 这里的this为new出来的 B{} this.y = y // 这里的this为new出来的 B{} }) var b = new B(30, 40) console.log(b) // {x: 30, y: 40}
_createClass
function _createClass(Constructor, protoProps, staticProps) { // 其中Constructor为f B(x,y),创造的一个ES5构造函数 // protoProps :undefined 属性 // staticProps: undefined 静态属性 if (protoProps) _defineProperties(Constructor.prototype, protoProps) if (staticProps) _defineProperties(Constructor, staticProps) Object.defineProperty(Constructor, 'prototype', { writable: false }) return Constructor // 返回f B(x,y) }
_classCallCheck
function _classCallCheck(instance, Constructor) { // instance = B{} 由new创造出来 // Constructor = f B(x, y) if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function') } }
_defineProperty
function _defineProperty(obj, key, value) { // obj = B{} // key = "x" // value = 1 key = _toPropertyKey(key) // 取到原始值key if (key in obj) { // 如果key是实例属性或者在原型链上,就做劫持 Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }) } else { // 不在的话,就添加key obj[key] = value } return obj // 返回实例对象 }
_toPropertyKey
function _toPropertyKey(arg) { // arg = "x" var key = _toPrimitive(arg, 'string') // "x" return _typeof(key) === 'symbol' ? key : String(key) }
_toPrimitive
function _toPrimitive(input, hint) { // input = "x" // hint = "string" // 如果input是原始值,并且不等于null,则直接返回 if (_typeof(input) !== 'object' || input === null) return input var prim = input[Symbol.toPrimitive] // 如果是对象,则需要拆箱得到原始值 if (prim !== undefined) { // 如果是不等于undefined,则表示有原始值 var res = prim.call(input, hint || 'default') if (_typeof(res) !== 'object') return res throw new TypeError('@@toPrimitive must return a primitive value.') } return (hint === 'string' ? String : Number)(input) // 如果是undefined则表示,没有取到原始值,需要继续拆箱调用Sting("x")取到原始值 }
_typeof
function _typeof(obj) { // obj = "x" '@babel/helpers - typeof' // babel提供的解析模块 return ( (_typeof = // 验证是否支持Symbol 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) { return typeof obj // "string" } // 支持Symbol,则_typeof = fucntion(obj){return typeof obj} : function (obj) { // 不支持Symbol的话,则会判断当前的单一职责,保证一个实例的情况 return obj && 'function' == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj // "string" }), _typeof(obj) ) }
_defineProperties
function _defineProperties(target, props) { // target = Constructor.prototype // props = 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, _toPropertyKey(descriptor.key), descriptor) } }
静态属性无法被实例化
关于class的继承
我们有如下代码
// class B class B { static q = 1; m = 3; constructor(x, y){ this.x = x; this.y = y; } } // class E class E extends B { constructor(x,y){ super(x,y) this.x = x; this.y =y } m = 10; n = 20; } const e = new E(100,200) const b = new B(30,40) console.log(e); console.log(b);
执行结果:
代码降级:
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } var B = /*#__PURE__*/_createClass(function B(x, y) { _classCallCheck(this, B); _defineProperty(this, "m", 3); this.x = x; this.y = y; }); _defineProperty(B, "q", 1); var b = new B(30, 40); console.log(b); var E = /*#__PURE__*/function (_B) { _inherits(E, _B); // _B为f B(x,y) E 为f E(x, y) var _super = _createSuper(E); function E(x, y) { var _this; _classCallCheck(this, E); _this = _super.call(this, x, y); _defineProperty(_assertThisInitialized(_this), "m", 10); _defineProperty(_assertThisInitialized(_this), "n", 20); _this.x = x; _this.y = y; return _this; } return _createClass(E); }(B); var e = new E(100, 200); console.log(e);
在这里我们看到了super
关键字被_inherits
、_createSuper
代替,extends
关键字也被函数替代,那么我们来研究一下这个代码。
_inherits
function _inherits(subClass, superClass) { // 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 } }) Object.defineProperty(subClass, 'prototype', { writable: false }) // 绑定子类原型 if (superClass) _setPrototypeOf(subClass, superClass) }
_setPrototypeOf
function _setPrototypeOf(o, p) { // o为子类的构造函数,p为父类的构造函数 _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p return o } return _setPrototypeOf(o, p) // 绑定原型 }
_createSuper
function _createSuper(Derived) { // Derived = f E(x,y) // 校验能不能用Reflect var hasNativeReflectConstruct = _isNativeReflectConstruct() return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), // 获得原型对象 result // 创建实例结果 if (hasNativeReflectConstruct) { // 如果能用Reflect,则调用Reflect.construct来创建实例对象 var NewTarget = _getPrototypeOf(this).constructor result = Reflect.construct(Super, arguments, NewTarget) } else { result = Super.apply(this, arguments) // 不能则把父类当做普通函数执行,this改变为子类实例对象 } return _possibleConstructorReturn(this, result) } }
_isNativeReflectConstruct
function _isNativeReflectConstruct() { // 判断是否可用Reflect, 不可被new,因为没有construct 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 } }
_getPrototypeOf
// 获取原型对象 function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o) } return _getPrototypeOf(o) }
_possibleConstructorReturn
、_assertThisInitialized
则是检验子类constructor
规则与实例存在与否。 之后便是走_createclass
那一套逻辑,所以这就是class
继承相关的东西,跟ES5
中的组合寄生继承实现的很类似。
总结
经过这么一转换,一阅读,我们不仅仅知道了class
类的一个本身的概念,而且还知道了他的一个实现原理,能够深入了解他的一个实例化的过程,当我们在被问到class
类没有constructor
还能被new吗?
以上就是无constructor的class类还能new吗问题解析的详细内容,更多关于无constructor class类new的资料请关注脚本之家其它相关文章!