闭包是一项功能,允许函数访问在相同作用域级别(词法作用域)中声明的所有其他变量和函数。
JavaScript 中的闭包与 Java 中的私有方法具有类似的用途,允许您创建私有变量并封装功能。
function outerFunction() { let outerVariable = 'I am from outer scope'; function innerFunction() { console.log(outerVariable); // Accessing outerVariable from the outer scope } return innerFunction; // Return the inner function } const closureFunction = outerFunction(); // Call outerFunction, which returns innerFunction closureFunction(); // Outputs: I am from outer scope
function handleCount() { let count = 0; return { increment: () => { count++; return count; }, decrement: () => { count--; return count; }, getCount: () => { return count; }, }; } const counter = handleCount(); console.log(counter.increment()); // Outputs: 1 console.log(counter.increment()); // Outputs: 2 console.log(counter.getCount()); // Outputs: 2 console.log(counter.decrement()); // Outputs: 1 console.log(counter.getCount()); // Outputs: 1
以上是掌握 JavaScript 中的闭包:了解范围、封装和性能的详细内容。更多信息请关注PHP中文网其他相关文章!