iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >无constructor的class类还能new吗
  • 503
分享到

无constructor的class类还能new吗

2023-07-05 10:07:52 503人浏览 安东尼
摘要

本篇内容主要讲解“无constructor的class类还能new吗”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“无constructor的class类还能new吗”吧!前言某一天晚上跟&quo

本篇内容主要讲解“无constructor的class类还能new吗”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“无constructor的class类还能new吗”吧!

前言

某一天晚上跟"混子瑶"聊天,下面模拟一下对话情景。

我:混子瑶,今天学了什么啊?

混子瑶:今天学习了typescriptclass类高级类型啊!(然后发了一张截图...,图上有明显的两个类 )

 class Point { x: number; y: number }; class Point2D ( x: number; y: number }; const p: Point = new Point2D();

我:Point2D都没有constructor,它能被new吗?

混子瑶:可以啊,你看它又没报错:

无constructor的class类还能new吗

我:这么神奇的嘛?

混子瑶: emmmm...

果真是这么神奇的嘛?来试一下不就知道咯!

class语法糖

classes6提供的一个语法糖,本质是一个函数,它具有constructorstatic默认方法... 咦?既然constructorclass类默认的,那岂不是显示,隐式都会默认去调用吗?文章的标题不就是一个子虚乌有的吗? 我们上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 = _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 = _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 =  _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)  }}

静态属性无法被实例化

无constructor的class类还能new吗

关于class的继承

我们有如下代码

// class Bclass B {  static q = 1;  m = 3;  constructor(x, y){    this.x = x;    this.y = y;  }}// class Eclass 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);

执行结果:

无constructor的class类还能new吗

代码降级:

"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 = _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 = 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中的组合寄生继承实现的很类似。

到此,相信大家对“无constructor的class类还能new吗”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

--结束END--

本文标题: 无constructor的class类还能new吗

本文链接: https://www.lsjlt.com/news/351005.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 无constructor的class类还能new吗
    本篇内容主要讲解“无constructor的class类还能new吗”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“无constructor的class类还能new吗”吧!前言某一天晚上跟&quo...
    99+
    2023-07-05
  • 无constructor的class类还能new吗问题解析
    目录前言class语法糖_createClass_classCallCheck_defineProperty_toPropertyKey_toPrimitive_typeof_def...
    99+
    2023-03-07
    constructor class类new class类new
  • UniApp中的UL还能用吗?
    UniApp是一个跨平台的开发框架,开发者可以采用一套代码开发出微信小程序、支付宝小程序、H5、App等多个平台的应用。UniApp提供了很多组件可以方便快捷的开发应用,其中UL组件是常用的列表组件。然而,最近有些开发者发现当使用UL组件时...
    99+
    2023-05-14
  • 已注册的域名还能抢注吗
    已注册的域名还能抢注吗?在互联网时代,域名已经成为企业、个人在网络世界中的重要身份标识。由于域名的独特性和价值,很多人常常会有一个疑问:已经被注册的域名是否还有机会被抢注?本文将探讨这个问题,并介绍一些相关的策略和注意事项。 随着互联网的...
    99+
    2024-01-23
    已注册的域名还能抢注吗 注册域名抢注 域名知识
  • 浏览器无痕浏览还能查到记录吗,如何开启无痕模式
    一些朋友对浏览器的无痕浏览比较好奇,是不是用这个无痕模式浏览网站,就能瞒天过海了?使用浏览器的无痕浏览还能查到记录吗?今天针对这些问题我们来聊一聊,如何开启无痕模式,浏览器无痕模式是否真的“无痕”?   什么是无痕浏览? 浏览器无痕浏览指...
    99+
    2023-09-10
    服务器 前端 html
  • 解决@RequestBody使用不能class类型匹配的问题
    @RequestBody不能class类型匹配 在首次第一次尝试使用@RequestBody注解 开始加载字符串使用post提交(貌似只能post),加Json数据格式传输的时候, ...
    99+
    2024-04-02
  • 买的阿里云服务器可以退吗现在还能退吗
    您好,如果您在阿里云购买的服务器可以退款,那么您可以在阿里云官网上退款页面上填写退货申请并等待退款。阿里云退款流程可能需要一定时间,请耐心等待。 此外,如果您在购买阿里云服务器时未满足条件,例如付款时未选择优质服务或者服务器已被关闭等问题...
    99+
    2023-10-26
    还能 阿里 服务器
  • 买的阿里云服务器可以退吗现在还能退吗安全吗
    您好,阿里云提供了两种退款方式,一种是在线退款,另一种是在线交易退款。其中在线交易退款需要等待24-48小时审批,并且只适用于信用评级高的订单。而在线交易退款需要等待3-5个工作日审批,审批通过后会立即退款到支付宝账户中。 如果您需要退款...
    99+
    2023-10-26
    还能 阿里 服务器
  • 买的阿里云服务器可以退吗现在还能用吗安全吗
    您好,阿里云提供7×24小时的在线支持服务,您可以通过在线客服或者联系阿里云客服,了解您在购买服务器时可以享受的售后服务,以及如何退款的相关信息。 关于安全问题,阿里云一直致力于为用户提供安全可靠的云计算服务,并不断提升系统安全性和加密技...
    99+
    2023-10-26
    阿里 能用 服务器
  • 企业邮箱过期的文件还能找回吗
    企业邮箱过期的文件还能找回吗?企业邮箱作为现代商业中不可或缺的沟通工具,承载着大量的重要文件和信息。然而,由于各种原因,有时候我们可能会忽视企业邮箱中文件的过期问题。那么,一旦文件在企业邮箱中过期了,还能找回吗?本文将探讨这个问题,并提供...
    99+
    2024-01-23
    企业邮箱过期文件 企业邮箱过期的文件还能找回吗 企业邮箱知识
  • Git是LeetCode的必备技能吗?还是JavaScript更重要?
    在当今的软件开发领域,Git和JavaScript都是非常重要的技能。Git是一种版本控制系统,而JavaScript是一种广泛使用的编程语言。那么,在LeetCode的练习和实际开发中,哪种技能更重要呢?本文将会对这个问题进行探讨。 G...
    99+
    2023-09-02
    git javascript leetcode
  • 云服务器干什么用的多啊现在还能用吗安全吗
    云服务器是一种提供计算服务的方式,它允许用户通过互联网访问、存储、处理和共享数据,无需自己安装软件和硬件设备。云服务器可以为个人、企业或组织提供高性能的计算能力,以及灵活的扩展能力和资源调度能力。 云服务器是一种常见的数据存储和处理方式,...
    99+
    2023-10-27
    能用 什么用 多啊
  • 买的阿里云服务器可以退吗现在还能用吗苹果11
    首先,你需要联系阿里云客服并提供服务器的详细信息和购买时间。 阿里云客服将为你提供退款和重新开通服务的支持,具体操作请参考阿里云官方文档:https://cloud.aliyun.com/service/restart/detail/20...
    99+
    2023-10-28
    阿里 能用 苹果
  • 云服务器干什么用的多啊现在还能用吗
    云服务器是一种提供服务器托管、备份和数据存储服务的云计算平台。它主要用于存储大量的数据,例如照片、视频、音频和文档等等。在云服务器中,存储的数据可以通过虚拟化技术将其分布在多个服务器上,从而减少了单个服务器的压力,提高了服务器的利用率。除此...
    99+
    2023-10-26
    能用 什么用 多啊
  • 买的阿里云服务器可以退吗现在还能用吗苹果手机
    我想了解,阿里云的服务器是否有可能出现无法使用的情况,这是否会影响我的手机使用?经过查找相关资料,我发现,阿里云的服务器可能会受到一些安全风险的影响,导致无法正常使用。因此,我需要尽快了解具体的情况,以便决定是否要采取相关措施。 经过咨询...
    99+
    2023-10-27
    阿里 能用 苹果
  • 云服务器干什么用的多啊现在还能用吗安全吗苹果
    云服务器可以帮助我们实现资源共享和数据处理,这对于企业和个人来说非常有意义。例如,在一个公司里,员工可以在自己的服务器上存储和处理大量数据,同时将这些数据上传到云服务器上,这可以让公司的服务器资源得到充分利用。此外,公司的客户可以通过云服务...
    99+
    2023-10-27
    能用 什么用 多啊
  • win7升级win10原来的软件还能用吗详细介绍
    未来微软将不再提供对win7系统的支持,不会再进行安全修复和更新。而继续使用win7系统将会极大的增加病毒和恶意软件攻击的风险,那么我们的win7升级win10原来的软件还能用吗,下面我们就来看看详细的介绍。1、如果不确定该软件是否因为兼容...
    99+
    2023-07-12
  • win7无法开启系统还原功能的三个原因分析
    大家都知道,Windows7操作系统中有自带系统还原功能,可以帮助我们在遇到系统问题时不需要重装系统,也不会破坏数据文件的前提下使系统回到工作状态,不过最近有一使用番茄花园win7系统的用户反映说他要开启系统还原功能的时...
    99+
    2023-06-17
    win7开启系统还原 win7如何开启系统还原 win7关闭系统还原功能 系统还原 原因 win7 功能
  • 你的对象被人从网络传输走了还能回来吗?
    🍎 博客主页:@风一样的美狼子 🍎 欢迎关注:👍点赞🍃收藏🔥留言 🍎系列专栏: 《云平台实战》、《Linux随你玩-实操》 ἴ...
    99+
    2023-08-30
    java 开发语言 后端
  • 数据库中删用户删表空间的操作还能恢复吗
    这篇文章主要讲解了“数据库中删用户删表空间的操作还能恢复吗”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“数据库中删用户删表空间的操作还能恢复吗”吧!有一次在...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作