無constructor的class類還能new嗎問題解析
前言
某一天晚上跟"混子瑤"聊天,下面模擬一下對話情景。
我:混子瑤,今天學(xué)了什么???
混子瑤:今天學(xué)習(xí)了TypeScript
的class
類高級類型啊!(然后發(fā)了一張截圖...,圖上有明顯的兩個類 )
class Point { x: number; y: number }; class Point2D ( x: number; y: number }; const p: Point = new Point2D();
我:Point2D
都沒有constructor
,它能被new
嗎?
混子瑤:可以啊,你看它又沒報錯:
我:這么神奇的嘛?
混子瑤: emmmm...
果真是這么神奇的嘛?來試一下不就知道咯!
class語法糖
class
是ES6
提供的一個語法糖,本質(zhì)是一個函數(shù),它具有constructor
,static
默認(rèn)方法... 咦?既然constructor
是class
類默認(rèn)的,那豈不是顯示,隱式都會默認(rèn)去調(diào)用嗎?文章的標(biāo)題不就是一個子虛烏有的嗎? 我們上babel來進(jìn)行一下語法降級。
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
轉(zhuǎn)化成了ES5
代碼,更能證明class只是一個語法糖,本質(zhì)只是一個函數(shù)。那我們來研究一下這些函數(shù)吧!????????
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),創(chuàng)造的一個ES5構(gòu)造函數(shù) // protoProps :undefined 屬性 // staticProps: undefined 靜態(tài)屬性 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創(chuàng)造出來 // 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是實(shí)例屬性或者在原型鏈上,就做劫持 Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }) } else { // 不在的話,就添加key obj[key] = value } return obj // 返回實(shí)例對象 }
_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則表示,沒有取到原始值,需要繼續(xù)拆箱調(diào)用Sting("x")取到原始值 }
_typeof
function _typeof(obj) { // obj = "x" '@babel/helpers - typeof' // babel提供的解析模塊 return ( (_typeof = // 驗(yàn)證是否支持Symbol 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) { return typeof obj // "string" } // 支持Symbol,則_typeof = fucntion(obj){return typeof obj} : function (obj) { // 不支持Symbol的話,則會判斷當(dāng)前的單一職責(zé),保證一個實(shí)例的情況 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 // 設(shè)置不可枚舉 靜態(tài)屬性無法被實(shí)例化 descriptor.configurable = true // 可擴(kuò)展 if ('value' in descriptor) descriptor.writable = true // 科協(xié) Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor) } }
靜態(tài)屬性無法被實(shí)例化
關(guān)于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);
執(zhí)行結(jié)果:
代碼降級:
"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
關(guān)鍵字被_inherits
、_createSuper
代替,extends
關(guān)鍵字也被函數(shù)替代,那么我們來研究一下這個代碼。
_inherits
function _inherits(subClass, superClass) { // subClass為子類的構(gòu)造函數(shù),superClass為父類的構(gòu)造函數(shù) if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function') } // 創(chuàng)建子類的原型 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為子類的構(gòu)造函數(shù),p為父類的構(gòu)造函數(shù) _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) // 校驗(yàn)?zāi)懿荒苡肦eflect var hasNativeReflectConstruct = _isNativeReflectConstruct() return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), // 獲得原型對象 result // 創(chuàng)建實(shí)例結(jié)果 if (hasNativeReflectConstruct) { // 如果能用Reflect,則調(diào)用Reflect.construct來創(chuàng)建實(shí)例對象 var NewTarget = _getPrototypeOf(this).constructor result = Reflect.construct(Super, arguments, NewTarget) } else { result = Super.apply(this, arguments) // 不能則把父類當(dāng)做普通函數(shù)執(zhí)行,this改變?yōu)樽宇悓?shí)例對象 } return _possibleConstructorReturn(this, result) } }
_isNativeReflectConstruct
function _isNativeReflectConstruct() { // 判斷是否可用Reflect, 不可被new,因?yàn)闆]有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
則是檢驗(yàn)子類constructor
規(guī)則與實(shí)例存在與否。 之后便是走_createclass
那一套邏輯,所以這就是class
繼承相關(guān)的東西,跟ES5
中的組合寄生繼承實(shí)現(xiàn)的很類似。
總結(jié)
經(jīng)過這么一轉(zhuǎn)換,一閱讀,我們不僅僅知道了class
類的一個本身的概念,而且還知道了他的一個實(shí)現(xiàn)原理,能夠深入了解他的一個實(shí)例化的過程,當(dāng)我們在被問到class
類沒有constructor
還能被new嗎?
以上就是無constructor的class類還能new嗎問題解析的詳細(xì)內(nèi)容,更多關(guān)于無constructor class類new的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Typescript中extends關(guān)鍵字的基本使用
extends表示具體的泛型類型只能是object類型,某個變量如果能斷言成object類型[變量as object],那么這個變量的類型符合T extends object,下面這篇文章主要給大家介紹了關(guān)于Typescript中extends關(guān)鍵字基本使用的相關(guān)資料,需要的朋友可以參考下2022-08-08javascript 中事件冒泡和事件捕獲機(jī)制的詳解
這篇文章主要介紹了javascript 中事件冒泡和事件捕獲機(jī)制的詳解的相關(guān)資料,網(wǎng)上的相關(guān)資料有很多,但是講的不是多清楚,通過本文希望能讓大家理解掌握,需要的朋友可以參考下2017-09-09點(diǎn)擊按鈕或鏈接不跳轉(zhuǎn)只刷新頁面的腳本整理
點(diǎn)擊按鈕或鏈接時不跳轉(zhuǎn)只刷新頁面,在某些情況下還是比較實(shí)用的,下面整理些不錯的示例,感興趣的朋友可以參考下2013-10-10基于JS實(shí)現(xiàn)01支付后的10秒倒計(jì)時
這是一個通過js實(shí)現(xiàn)的支付后的頁面,點(diǎn)擊支付會跳出一個彈窗,提示你是否要確定支付,確定后進(jìn)入付后界面,該頁面有著10秒倒計(jì)時,計(jì)時結(jié)束后便會返回原界面,也可以選擇立刻返回,來返回主頁面,這篇文章主要介紹了基于JS實(shí)現(xiàn)01支付后的10秒倒計(jì)時,需要的朋友可以參考下2023-03-03JavaScript中while循環(huán)的基礎(chǔ)使用教程
這篇文章主要給大家介紹了關(guān)于JavaScript中while循環(huán)的基礎(chǔ)使用教程,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用JavaScript具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08BootstrapValidator驗(yàn)證用戶名已存在(ajax)
這篇文章主要為大家詳細(xì)介紹了BootstrapValidator驗(yàn)證用戶名已存在,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11詳解微信小程序?qū)崿F(xiàn)WebSocket心跳重連
這篇文章主要介紹了詳解微信小程序?qū)崿F(xiàn)WebSocket心跳重連,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07