局部变量与全局变量:程序员权威指南
作为一名经验丰富的程序员,您在构建应用程序时做出的一个核心决策是确定何时使用局部变量和全局变量。正确地做到这一点对于代码质量、性能和减少未来的麻烦有着巨大的影响!
在这份权威指南中,我们将介绍何时以及为何利用本地和全局变量、有效使用它们的指南,并用可立即应用的代码示例进行说明。
首先,我们不断提到的这些变量到底是什么?
变量是内存中的命名数据存储,我们的程序可以对其进行操作。例如:
int counter = 0;
counter
范围是指程序中变量可访问的位置。局部变量仅存在于声明它们的块或函数中:
function incrementCounter() {
let counter = 0;
counter++;
}
// counter not accessible here!
同时,全局变量在函数外部声明,可以在任何地方使用:
// Declared globally
let counter = 0;
function incrementCounter() {
counter++;
}
总结来说:
🔹 用于函数内所需的临时数据
🔹 将功能与应用程序的其余部分隔离
sum()
function sum(numbers) {
let total = 0; // Local variable
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
// Can‘t access total or i here!
total和i
全局变量启用。使用它们:
例如:
// Shared constant
const API_KEY = "1234abcd";
// Shared state
let userData = {};
function fetchUserData() {
userData = http.get("url", API_KEY);
}
这里API_KEY和userData
表现。 Let's examine local versus global variable access speed in JavaScript:
| 局部变数 | 0.35 |
| 1.5 |
。
局部变量仅在函数执行时存在。一旦函数退出,它们就会自动销毁:
function logger() {
let message = "Hello world";
console.log(message);
}
logger(); // Prints "Hello world"
console.log(message); // Error, message doesn‘t exist!
相反,全局变量会一直存在,直到程序终止:
let message = "Hello world!"; // Global variable
function logger() {
console.log(message);
}
logger(); // Prints "Hello world!"
// message still exists here
选择变量范围时请仔细考虑所需的生命周期。
。 Each invocation pushes a separate stack frame containing the function's local variables:
Stack frame 3
Local var a: 1
Stack frame 2
Local var a: 2
Stack frame 1
Local var a: 3
Heap:
Global var b: 4
Global var c: "text"
对于局部变量:
:
一般来说:
Hopefully these explanations and tips on leveraging local vs global variables proves helpful for your future coding!如果您还有其他问题,请告诉我。
