1. 声明不可变性
1.1 基本类型的不可变性
const name = 'John';
name = 'Jane';
const age = 25;
age = 26;
const isValid = true;
isValid = false;
1.2 引用类型的可变性
const person = {
name: 'John',
age: 25
};
person.name = 'Jane';
person.age = 26;
person = {};
const numbers = [1, 2, 3];
numbers.push(4);
numbers[0] = 0;
numbers = [];
2. 声明必须赋值
2.1 正确的声明方式
const name = 'John';
const age = 25;
const person = { name: 'John' };
2.2 错误的声明方式
const name;
const age;
age = 25;
3. 不允许重复定义
3.1 同一作用域重复声明
const name = 'John';
const name = 'Jane';
const age = 25;
var age = 26;
let age = 26;
3.2 不同作用域的声明
const x = 1;
if (true) {
const x = 2;
console.log(x);
}
console.log(x);
function example() {
const x = 3;
console.log(x);
}
4. 不具有变量提升
4.1 变量提升问题
console.log(name);
const name = 'John';
function example() {
console.log(age);
const age = 25;
}
5. 暂时性死区(TDZ)
5.1 基本概念
{
console.log(name);
const name = 'John';
}
5.2 复杂场景中的 TDZ
function example(x = y, y = 1) {
return [x, y];
}
example();
if (true) {
console.log(value);
const value = 123;
}
6. 不与顶层对象挂钩
6.1 与全局对象的关系
const name = 'John';
console.log(window.name);
const age = 25;
console.log(global.age);
7. const 定义的数据修改限制
7.1 使用 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 userList = [];
8. 实际应用场景
8.1 模块常量
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 组件中的使用
const DEFAULT_PROPS = Object.freeze({
theme: 'light',
size: 'medium'
});
const MyComponent = (props) => {
const finalProps = { ...DEFAULT_PROPS, ...props };
return <div className={finalProps.theme}>{/* ... */}</div>;
};
const VALIDATION_RULES = Object.freeze({
required: true,
minLength: 3,
maxLength: 20
});
export default {
data() {
return {
rules: VALIDATION_RULES
};
}
};