JavaScript变量声明方式详解

在JavaScript中,变量声明有几种不同的方式,每种都有其特定的用途和行为。下面我将详细解释这些声明方式的区别,并提供一个可视化演示页面。

主要变量声明方式

声明方式 作用域 是否可重复声明 是否可重新赋值 是否变量提升 暂时性死区
var 函数作用域
let 块级作用域 否(有提升但行为不同)
const 块级作用域 否(但可修改对象属性) 否(有提升但行为不同)

其他声明方式

  • function - 函数声明,具有函数作用域和变量提升
  • class - ES6类声明,具有块级作用域,不会变量提升
  • import - 模块导入,具有块级作用域,是只读的

可视化演示

下面是一个交互式演示,帮助理解不同变量声明方式的区别:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript变量声明方式详解</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
color: #333;
line-height: 1.6;
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 40px;
padding: 20px;
background: rgba(255, 255, 255, 0.8);
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
h1 {
color: #2c3e50;
margin-bottom: 10px;
}
.description {
color: #7f8c8d;
max-width: 800px;
margin: 0 auto;
}
.comparison-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
background: white;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.comparison-table th, .comparison-table td {
padding: 15px;
text-align: left;
border-bottom: 1px solid #e0e0e0;
}
.comparison-table th {
background-color: #3498db;
color: white;
font-weight: 600;
}
.comparison-table tr:last-child td {
border-bottom: none;
}
.comparison-table tr:hover {
background-color: #f5f5f5;
}
.demo-section {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin-bottom: 40px;
}
.demo-box {
flex: 1;
min-width: 300px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.demo-box h3 {
color: #2c3e50;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
}
.code-block {
background: #2d3436;
color: #f5f6fa;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
overflow-x: auto;
font-family: 'Consolas', monospace;
}
.btn {
display: inline-block;
background: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin-top: 10px;
transition: background 0.3s;
}
.btn:hover {
background: #2980b9;
}
.output {
margin-top: 15px;
padding: 15px;
background: #f8f9fa;
border-radius: 5px;
border-left: 4px solid #3498db;
}
footer {
text-align: center;
margin-top: 40px;
color: #7f8c8d;
font-size: 0.9em;
}
.highlight {
background-color: #fffacd;
padding: 2px 5px;
border-radius: 3px;
}
@media (max-width: 768px) {
.demo-section {
flex-direction: column;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>JavaScript变量声明方式详解</h1>
<p class="description">了解var, let, const等变量声明方式的区别,以及它们的作用域、提升行为和其他特性。</p>
</header>

<table class="comparison-table">
<thead>
<tr>
<th>声明方式</th>
<th>作用域</th>
<th>是否可重复声明</th>
<th>是否可重新赋值</th>
<th>是否变量提升</th>
<th>暂时性死区</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="highlight">var</span></td>
<td>函数作用域</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><span class="highlight">let</span></td>
<td>块级作用域</td>
<td></td>
<td></td>
<td>否(有提升但行为不同)</td>
<td></td>
</tr>
<tr>
<td><span class="highlight">const</span></td>
<td>块级作用域</td>
<td></td>
<td>否(但可修改对象属性)</td>
<td>否(有提升但行为不同)</td>
<td></td>
</tr>
<tr>
<td><span class="highlight">function</span></td>
<td>函数作用域</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><span class="highlight">class</span></td>
<td>块级作用域</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><span class="highlight">import</span></td>
<td>模块作用域</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>

<div class="demo-section">
<div class="demo-box">
<h3>var 声明演示</h3>
<div class="code-block">
// 函数作用域和变量提升示例
console.log(a); // 输出: undefined (变量提升)
var a = 10;
console.log(a); // 输出: 10

if (true) {
var a = 20; // 同一个变量
console.log(a); // 输出: 20
}
console.log(a); // 输出: 20 (没有块级作用域)
</div>
<button class="btn" onclick="runVarDemo()">运行演示</button>
<div class="output" id="var-output"></div>
</div>

<div class="demo-box">
<h3>let 和 const 声明演示</h3>
<div class="code-block">
// 块级作用域示例
let x = 10;
const y = 20;

if (true) {
let x = 30; // 不同的变量
const y = 40; // 不同的常量
console.log(x); // 输出: 30
console.log(y); // 输出: 40
}

console.log(x); // 输出: 10 (块级作用域)
console.log(y); // 输出: 20

// const 不能重新赋值
// y = 30; // 会抛出错误
</div>
<button class="btn" onclick="runLetConstDemo()">运行演示</button>
<div class="output" id="let-const-output"></div>
</div>
</div>

<div class="demo-section">
<div class="demo-box">
<h3>function 声明演示</h3>
<div class="code-block">
// 函数声明提升
console.log(sayHello); // 输出: function sayHello() {...}
console.log(sayHello()); // 输出: "Hello!"

function sayHello() {
return "Hello!";
}

// 函数表达式不会提升
// console.log(sayGoodbye); // 错误: sayGoodbye is not defined
var sayGoodbye = function() {
return "Goodbye!";
};
console.log(sayGoodbye()); // 输出: "Goodbye!"
</div>
<button class="btn" onclick="runFunctionDemo()">运行演示</button>
<div class="output" id="function-output"></div>
</div>

<div class="demo-box">
<h3>class 声明演示</h3>
<div class="code-block">
// class 声明不会提升
// const p = new Person(); // 错误: Person is not defined

class Person {
constructor(name) {
this.name = name;
}

greet() {
return `Hello, my name is ${this.name}`;
}
}

const john = new Person("John");
console.log(john.greet()); // 输出: "Hello, my name is John"

// class 表达式
const Animal = class {
constructor(name) {
this.name = name;
}
};

const dog = new Animal("Dog");
console.log(dog.name); // 输出: "Dog"
</div>
<button class="btn" onclick="runClassDemo()">运行演示</button>
<div class="output" id="class-output"></div>
</div>
</div>

<footer>
<p>JavaScript变量声明方式详解 &copy; 2023</p>
</footer>
</div>

<script>
function runVarDemo() {
const output = document.getElementById('var-output');
output.innerHTML = '';

// 使用try-catch来捕获可能的错误
try {
let log = [];

// 模拟console.log
const mockLog = (msg) => log.push(msg);

// 保存原始console.log
const originalLog = console.log;

// 重写console.log
console.log = mockLog;

// 运行演示代码
eval(`
console.log(a); // 输出: undefined (变量提升)
var a = 10;
console.log(a); // 输出: 10

if (true) {
var a = 20; // 同一个变量
console.log(a); // 输出: 20
}
console.log(a); // 输出: 20 (没有块级作用域)
`);

// 恢复console.log
console.log = originalLog;

// 显示输出
output.innerHTML = log.join('<br>');
} catch (error) {
output.innerHTML = `错误: ${error.message}`;
}
}

function runLetConstDemo() {
const output = document.getElementById('let-const-output');
output.innerHTML = '';

try {
let log = [];
const originalLog = console.log;
console.log = mockLog;

function mockLog(msg) {
log.push(msg);
}

eval(`
let x = 10;
const y = 20;

if (true) {
let x = 30; // 不同的变量
const y = 40; // 不同的常量
console.log(x); // 输出: 30
console.log(y); // 输出: 40
}

console.log(x); // 输出: 10 (块级作用域)
console.log(y); // 输出: 20

// const 不能重新赋值
// y = 30; // 会抛出错误
`);

console.log = originalLog;
output.innerHTML = log.join('<br>');
} catch (error) {
output.innerHTML = `错误: ${error.message}`;
}
}

function runFunctionDemo() {
const output = document.getElementById('function-output');
output.innerHTML = '';

try {
let log = [];
const originalLog = console.log;
console.log = mockLog;

function mockLog(msg) {
if (typeof msg === 'function') {
log.push('function ' + msg.name + '() {...}');
} else {
log.push(msg);
}
}

eval(`
console.log(sayHello); // 输出: function sayHello() {...}
console.log(sayHello()); // 输出: "Hello!"

function sayHello() {
return "Hello!";
}

// 函数表达式不会提升
// console.log(sayGoodbye); // 错误: sayGoodbye is not defined
var sayGoodbye = function() {
return "Goodbye!";
};
console.log(sayGoodbye()); // 输出: "Goodbye!"
`);

console.log = originalLog;
output.innerHTML = log.join('<br>');
} catch (error) {
output.innerHTML = `错误: ${error.message}`;
}
}

function runClassDemo() {
const output = document.getElementById('class-output');
output.innerHTML = '';

try {
let log = [];
const originalLog = console.log;
console.log = mockLog;

function mockLog(msg) {
log.push(msg);
}

eval(`
// class 声明不会提升
// const p = new Person(); // 错误: Person is not defined

class Person {
constructor(name) {
this.name = name;
}

greet() {
return "Hello, my name is " + this.name;
}
}

const john = new Person("John");
console.log(john.greet()); // 输出: "Hello, my name is John"

// class 表达式
const Animal = class {
constructor(name) {
this.name = name;
}
};

const dog = new Animal("Dog");
console.log(dog.name); // 输出: "Dog"
`);

console.log = originalLog;
output.innerHTML = log.join('<br>');
} catch (error) {
output.innerHTML = `错误: ${error.message}`;
}
}
</script>
</body>
</html>

关键点总结

  1. var:函数作用域,存在变量提升,可重复声明和重新赋值
  2. let:块级作用域,存在暂时性死区,不可重复声明但可重新赋值
  3. const:块级作用域,存在暂时性死区,不可重复声明和重新赋值(但对于对象和数组,内容可修改)
  4. function:函数声明具有函数作用域和提升特性
  5. class:类声明具有块级作用域,不存在提升
  6. import:模块导入是只读的,具有模块作用域

现代JavaScript开发中,推荐使用let和const代替var,因为它们提供了更可预测的作用域行为,有助于避免常见的错误。