ES6 const 使用总结

news/2025/2/6 14:49:32 标签: es6, javascript, 前端

1. 声明不可变性

1.1 基本类型的不可变性

// 基本类型声明后不能修改
const name = 'John';
name = 'Jane';  // TypeError: Assignment to constant variable

const age = 25;
age = 26;  // TypeError: Assignment to constant variable

const isValid = true;
isValid = false;  // TypeError: Assignment to constant variable

1.2 引用类型的可变性

// 对象的属性可以修改
const person = {
  name: 'John',
  age: 25
};
person.name = 'Jane';  // 正常工作
person.age = 26;      // 正常工作
person = {};          // TypeError: Assignment to constant variable

// 数组的元素可以修改
const numbers = [1, 2, 3];
numbers.push(4);     // 正常工作
numbers[0] = 0;      // 正常工作
numbers = [];        // TypeError: Assignment to constant variable

2. 声明必须赋值

2.1 正确的声明方式

// ✅ 声明时必须初始化
const name = 'John';
const age = 25;
const person = { name: 'John' };

2.2 错误的声明方式

// ❌ 不能只声明不赋值
const name;  // SyntaxError: Missing initializer in const declaration

// ❌ 不能先声明后赋值
const age;
age = 25;    // SyntaxError: Missing initializer in const declaration

3. 不允许重复定义

3.1 同一作用域重复声明

// ❌ 同一作用域不能重复声明
const name = 'John';
const name = 'Jane';  // SyntaxError: Identifier 'name' has already been declared

// ❌ 与其他声明方式混用也不行
const age = 25;
var age = 26;   // SyntaxError: Identifier 'age' has already been declared
let age = 26;   // SyntaxError: Identifier 'age' has already been declared

3.2 不同作用域的声明

// ✅ 不同作用域可以声明同名常量
const x = 1;
if (true) {
  const x = 2;  // 正常工作
  console.log(x);  // 2
}
console.log(x);  // 1

function example() {
  const x = 3;  // 正常工作
  console.log(x);  // 3
}

4. 不具有变量提升

4.1 变量提升问题

// ❌ 在声明前访问会报错
console.log(name);  // ReferenceError: Cannot access 'name' before initialization
const name = 'John';

// ❌ 在函数中也是一样
function example() {
  console.log(age);  // ReferenceError: Cannot access 'age' before initialization
  const age = 25;
}

5. 暂时性死区(TDZ)

5.1 基本概念

// 从作用域开始到变量声明前的区域称为暂时性死区
{
  console.log(name);  // ReferenceError: Cannot access 'name' before initialization
  const name = 'John';
}

5.2 复杂场景中的 TDZ

// 函数参数中的 TDZ
function example(x = y, y = 1) {
  return [x, y];
}
example();  // ReferenceError: Cannot access 'y' before initialization

// 条件语句中的 TDZ
if (true) {
  console.log(value);  // ReferenceError
  const value = 123;
}

6. 不与顶层对象挂钩

6.1 与全局对象的关系

// 浏览器环境
const name = 'John';
console.log(window.name);  // undefined

// Node.js 环境
const age = 25;
console.log(global.age);  // undefined

7. const 定义的数据修改限制

7.1 使用 Object.freeze() 实现真正的不可变

// 使用 Object.freeze() 冻结对象
const person = Object.freeze({
  name: 'John',
  age: 25,
  address: {
    city: 'New York'
  }
});

person.name = 'Jane';     // 静默失败或在严格模式下报错
person.age = 26;          // 静默失败或在严格模式下报错
person.address.city = 'LA';  // 仍然可以修改(浅冻结)

// 深度冻结函数
function deepFreeze(obj) {
  Object.keys(obj).forEach(prop => {
    if (typeof obj[prop] === 'object' && obj[prop] !== null) {
      deepFreeze(obj[prop]);
    }
  });
  return Object.freeze(obj);
}

// 使用深度冻结
const config = deepFreeze({
  api: {
    url: 'https://api.example.com',
    key: '123456'
  },
  settings: {
    timeout: 1000
  }
});

config.api.url = 'new-url';  // 无法修改
config.settings.timeout = 2000;  // 无法修改

7.2 使用 const 的最佳实践

// ✅ 用于不变的配置
const CONFIG = {
  API_URL: 'https://api.example.com',
  MAX_RETRIES: 3,
  TIMEOUT: 5000
};

// ✅ 用于引用类型时,明确表达意图
const userSettings = Object.freeze({
  theme: 'dark',
  notifications: true
});

// ✅ 用于函数声明
const calculateTotal = (items) => {
  return items.reduce((sum, item) => sum + item.price, 0);
};

// ❌ 避免对需要修改的数据使用 const
const userList = [];  // 如果需要修改数组,应该使用 let

8. 实际应用场景

8.1 模块常量

// constants.js
export const API_CONFIG = Object.freeze({
  BASE_URL: 'https://api.example.com',
  TIMEOUT: 5000,
  HEADERS: {
    'Content-Type': 'application/json'
  }
});

// 使用常量
import { API_CONFIG } from './constants';
fetch(\`\${API_CONFIG.BASE_URL}/users\`, {
  headers: API_CONFIG.HEADERS,
  timeout: API_CONFIG.TIMEOUT
});

8.2 React/Vue 组件中的使用

// React 组件
const DEFAULT_PROPS = Object.freeze({
  theme: 'light',
  size: 'medium'
});

const MyComponent = (props) => {
  const finalProps = { ...DEFAULT_PROPS, ...props };
  return <div className={finalProps.theme}>{/* ... */}</div>;
};

// Vue 组件
const VALIDATION_RULES = Object.freeze({
  required: true,
  minLength: 3,
  maxLength: 20
});

export default {
  data() {
    return {
      rules: VALIDATION_RULES
    };
  }
}; 

http://www.niftyadmin.cn/n/5843089.html

相关文章

java使用LibreOffice实现word转pdf

之前使用dom4j转换&#xff0c;依赖office&#xff1b; 网上还有Apache poi和itextpdf方式&#xff0c;尝试后发现复杂word&#xff0c;比如包含表格曲线等支持性不好。 最后发现 LibreOffice&#xff1a;不依赖office&#xff0c;免费&#xff0c;可跨平台 参考链接&#xf…

Ollama+deepseek+Docker+Open WebUI实现与AI聊天

1、下载并安装Ollama 官方网址&#xff1a;Ollama 安装好后&#xff0c;在命令行输入&#xff0c; ollama --version 返回以下信息&#xff0c;则表明安装成功&#xff0c; 2、 下载AI大模型 这里以deepseek-r1:1.5b模型为例&#xff0c; 在命令行中&#xff0c;执行&…

国防科大:双目标优化防止LLM灾难性遗忘

&#x1f4d6;标题&#xff1a;How to Complete Domain Tuning while Keeping General Ability in LLM: Adaptive Layer-wise and Element-wise Regularization &#x1f310;来源&#xff1a;arXiv, 2501.13669 &#x1f31f;摘要 &#x1f538;大型语言模型&#xff08;LLM…

产品经理的人工智能课 02 - 自然语言处理

产品经理的人工智能课 02 - 自然语言处理 1 自然语言处理是什么2 一个 NLP 算法的例子——n-gram 模型3 预处理与重要概念3.1 分词 Token3.2 词向量化表示与 Word2Vec 4 与大语言模型的交互过程参考链接 大语言模型&#xff08;Large Language Models, LLMs&#xff09;是自然语…

技术书籍写作与编辑沟通指南

引言 撰写技术书籍不仅仅是知识的输出过程&#xff0c;更是与编辑团队紧密合作的协同工作。优秀的技术书籍不仅依赖作者深厚的技术背景&#xff0c;还需要精准的表达、流畅的结构以及符合出版要求的编辑润色。因此&#xff0c;如何高效地与编辑沟通&#xff0c;确保书籍质量&a…

Android Studio:Application 和 Activity的区别

Application 和 Activity 是 Android 中非常重要的两个组件&#xff0c;它们分别负责不同的生命周期管理和应用的不同层次的操作。 Application 是应用级别的生命周期管理&#xff0c;它在整个应用运行时只有一个实例&#xff0c;负责应用的全局初始化和资源管理。Activity 是…

【PostgreSQL内核学习 —— (WindowAgg(二))】

WindowAgg WindowAggState 结构体窗口聚合行为ExecInitWindowAgg 函数ExecWindowAgg 函数代码逻辑解释&#xff1a;计算窗口偏移量代码逻辑详细解释&#xff1a; 代码逻辑解释&#xff1a;窗口聚合分区初始化与行推进逻辑代码逻辑详细解释&#xff1a; 代码逻辑解释&#xff1a…

Jupyterlab和notebook修改文件的默认存放路径的方法

文章目录 1.缘由2.操作流程2.1找到默认的路径2.2创建配置文件2.3修改配置文件内容2.4注意事项 1.缘由 我自己使用jupyterlab的时候&#xff0c;打开是在这个浏览器上面打开的&#xff0c;但是这个打开的文件路径显示的是C盘上面路径&#xff0c;所以这个就很麻烦&#xff0c;因…