Class转换func

123 阅读1分钟

将下列代码转写成普通构造函数的代码

class Example {
  constructor(name){
    this.name=name
  }
  func(){
    console.log(this.name)
  }
}

下面普通的写法

function Example(name){
  this.name=name  
}
Example.prototype.func = function () {
  console.log(this.name)
}

但这种写法还不够完整
下面有几点细节是需要补充的

  1. class中的代码是处于严格模式下的,所以需要在最上面加上use strict
  2. class只能通过new来调用,因此需要模拟这个方式,需要在代码里判断this的指向
  3. class中的方法是不能被枚举的,因此不能直接在原型中直接赋值func,应该采用Object.defineProperty,并且设置为enumerable:false
  4. class中的方法不能通过new调用,因此也需要判断this的指向

综上,完整版的写法为:

'use strict'
function Example(name){
  if(!(this instanceof Example)){
    throw new TypeError(
      '只能通过new来调用该函数'
    )
  }
  this.name=name  
}
Object.defineProperty(Example.prototype,'func',{
  value:function(){
    if(!(this instanceof Example)){
    throw new TypeError(
    'Class中的方法不能通过new来调用'
    )
  }
   console.log(this.name) 
  },
  enumerable:false
})

该题目出自抖音--渡一Web前端学习频道