【ES6】class关于Cannot access XXX before initialization的报错

在使用ES6 class定义类时遇到Cannot access before initialization错误,问题源于在自调用函数内部未先声明class。解决方案是将class声明置于自调用函数之前。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【Q】在使用class定义类的时候,由于在代码中使用了(function(){})自调用方法,没有先声明class类,出现了报错问题,代码如下:

报错:Cannot access 'Stack' before initialization

(function() {
  console.log(clacExp(["4", "13", "5", "/", "+"]));
})();

class Stack {
  constructor() {
    this._items = [];
  }
  push(item) {
    this._items.push(item);
  }
  pop() {
    return this._items.pop();
  }
  peek() {
    return this._items[this._items.length-1];
  }
  isEmpty() {
    return !this._items.length;
  }
  size() {
    return this._items.length;
  }
  clear() {
    this._items = [];
  }
}

function isOperator(str) {
  return ["+", "-", "*", "/"].includes(str);
}

function clacExp(exp) {
  let stack = new Stack();
  let current_str = null,
      expression1 = null,
      expression2 = null,
      exp_str = null,
      res = null;
  exp.map(function(item, index) {
    current_str = item;
    if (isOperator(current_str)) {
      expression2 = stack.pop();
      expression1 = sta
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值