[Console] Error: Cannot access 'xxx' before initialization

Article directory

error message

  • Example:
    insert image description here
  • Sample code:
// constants.js 文件:
export const ATTRIBUTION_FORM = {
    
    
  partition_type: '',
  data_resource_id: '',
  query_dates: [
    {
    
    
      date_dim: null,
      date_type: 'day',
      date_range: 1,
    },
  ],
  filters: [
    {
    
    
      logic: 'and',
      wheres: [],
    },
  ],
};
// create-crowd.js 文件:
import {
    
     ATTRIBUTION_FORM } from '@/commons/constants';

console.log(ATTRIBUTION_FORM)	// 报错

Solution

ES6: When the control flow of the program is instantiated in a new scope (module function or block scope), variables declared with let/const in this scope will be created in the scope first, but therefore It has not been lexically bound, so it cannot be accessed, and an error will be thrown if accessed. Therefore, the period between when the running process enters the scope to create variables and when the variables can be accessed is called a temporary dead zone.

  • wrong reason:
1. 在块作用域内,letconst 声明的变量被提升,但变量只是创建被提升,初始化并没有被提升。
2. 在初始化之前使用变量,就会形成一个暂时性死区。
3.let/const 声明的变量在未出现声明变量的那一行代码之前没有进行词法绑定,无法被访问。
  • Method background:
1. 我们知道,let/const作用域为块级作用域,变量不会提升;
2.var的作用域为全局作用域,可以进行变量提升,这也就是为什么var没有暂时性死区。
  • So here you can use var instead of const to solve this error, as a temporary solution.
// constants.js 文件:
export var ATTRIBUTION_FORM = {
    
    
  partition_type: '',
  data_resource_id: '',
  query_dates: [
    {
    
    
      date_dim: null,
      date_type: 'day',
      date_range: 1,
    },
  ],
  filters: [
    {
    
    
      logic: 'and',
      wheres: [],
    },
  ],
};

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/129949609