ES6 class转function

class 与 构造函数的区别

  1. calss只能使用new调用,不能普通调用(cannot be invoked without ‘new’);
    构造函数有两种来调用方法,普通调用和new调用
  2. class中的原型方法是不可枚举的,构造函数的原型方法可枚举
  3. class中的所有代码在严格模式下,构造函数中的代码在普通模式下
  4. class中的原型方法不能通过new调用,构造函数中原型方法可以用new调用
//class寫法
class Computer1 {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
  //原型方法,通過實例調用
  showPrice() {
    console.log(`這台${this.name}電腦的價格是${this.price}`);
  }
  //類的靜態方法,通過類調用
  static staticFun() {
    console.log("這是class的靜態方法");
  }
}


("use strict");
function Computer(name, age) {
  if (!new.target) {
    throw new Error("Computer cannot be invoked without new");
  }
  this.name = name;
  this.age = age;
}
Object.defineProperty(Computer.prototype, "showPrice", {
  value: function () {
    if (new.target) {
      throw new Error("showPrice is not a constructor");
    }
  },
  enumerable: false,
});


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值