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

【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 = stack.pop();
      exp_str = `${expression1}${current_str}${expression2}`;
      res = eval(exp_str);
      stack.push(res);
    } else {
      stack.push(current_str);
    }
  });
  return stack.peek();
}

【A】解决方法:

我们只需将class定义放在自调用方法前面声明即可解决,废话不多说,上代码:

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() {
  console.log(clacExp(["4", "13", "5", "/", "+"]));
})();

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 = stack.pop();
      exp_str = `${expression1}${current_str}${expression2}`;
      res = eval(exp_str);
      stack.push(res);
    } else {
      stack.push(current_str);
    }
  });
  return stack.peek();
}

 

你可能感兴趣的:(js,原生JS,JS,ES6)