最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

無(wú)constructor的class類還能new嗎問(wèn)題解析

 更新時(shí)間:2023年03月07日 14:19:13   作者:一溪之石  
這篇文章主要為大家介紹了無(wú)constructor的class類是否還能new的問(wèn)題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

前言

某一天晚上跟"混子瑤"聊天,下面模擬一下對(duì)話情景。

我:混子瑤,今天學(xué)了什么???

混子瑤:今天學(xué)習(xí)了TypeScriptclass類高級(jí)類型??!(然后發(fā)了一張截圖...,圖上有明顯的兩個(gè)類 )

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

我:Point2D都沒(méi)有constructor,它能被new嗎?

混子瑤:可以啊,你看它又沒(méi)報(bào)錯(cuò):

我:這么神奇的嘛?

混子瑤: emmmm...

果真是這么神奇的嘛?來(lái)試一下不就知道咯!

class語(yǔ)法糖

classES6提供的一個(gè)語(yǔ)法糖,本質(zhì)是一個(gè)函數(shù),它具有constructorstatic默認(rèn)方法... 咦?既然constructorclass類默認(rèn)的,那豈不是顯示,隱式都會(huì)默認(rèn)去調(diào)用嗎?文章的標(biāo)題不就是一個(gè)子虛烏有的嗎? 我們上babel來(lái)進(jìn)行一下語(yǔ)法降級(jí)。

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}
// 降級(jí)之后的代碼
"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降級(jí)把ES6轉(zhuǎn)化成了ES5代碼,更能證明class只是一個(gè)語(yǔ)法糖,本質(zhì)只是一個(gè)函數(shù)。那我們來(lái)研究一下這些函數(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出來(lái)的 B{}
  this.y = y // 這里的this為new出來(lái)的 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)造的一個(gè)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)造出來(lái)
  // 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í)例對(duì)象
}

_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] // 如果是對(duì)象,則需要拆箱得到原始值
  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則表示,沒(méi)有取到原始值,需要繼續(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的話,則會(huì)判斷當(dāng)前的單一職責(zé),保證一個(gè)實(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)屬性無(wú)法被實(shí)例化
    descriptor.configurable = true // 可擴(kuò)展
    if ('value' in descriptor) descriptor.writable = true // 科協(xié)
    Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor)
  }
}

靜態(tài)屬性無(wú)法被實(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é)果:

代碼降級(jí):

"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ù)替代,那么我們來(lái)研究一下這個(gè)代碼。

_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), // 獲得原型對(duì)象
      result // 創(chuàng)建實(shí)例結(jié)果
    if (hasNativeReflectConstruct) { // 如果能用Reflect,則調(diào)用Reflect.construct來(lái)創(chuàng)建實(shí)例對(duì)象
      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í)例對(duì)象
    }
    return _possibleConstructorReturn(this, result)
  }
}

_isNativeReflectConstruct

function _isNativeReflectConstruct() {
  // 判斷是否可用Reflect, 不可被new,因?yàn)闆](méi)有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

// 獲取原型對(duì)象
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)過(guò)這么一轉(zhuǎn)換,一閱讀,我們不僅僅知道了class類的一個(gè)本身的概念,而且還知道了他的一個(gè)實(shí)現(xiàn)原理,能夠深入了解他的一個(gè)實(shí)例化的過(guò)程,當(dāng)我們?cè)诒粏?wèn)到class類沒(méi)有constructor還能被new嗎?

以上就是無(wú)constructor的class類還能new嗎問(wèn)題解析的詳細(xì)內(nèi)容,更多關(guān)于無(wú)constructor class類new的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

岑溪市| 灵台县| 宝坻区| 康平县| 盐池县| 资溪县| 分宜县| 枣强县| 海口市| 丰镇市| 荆州市| 渝中区| 壶关县| 泉州市| 巩义市| 常宁市| 泸州市| 宣化县| 晋江市| 绥芬河市| 饶阳县| 兴和县| 托克托县| 宝应县| 汤阴县| 宾川县| 白河县| 景谷| 镇赉县| 宁阳县| 芜湖县| 沂源县| 贞丰县| 毕节市| 陆良县| 攀枝花市| 哈密市| 武冈市| 台安县| 乐山市| 梅州市|