首页 > 技术文章 > 闭包(closure)

sea-breeze 2019-03-07 14:51 原文

 

一 概述

 

闭包是函数和声明该函数的词法环境的组合。这个环境包含了这个闭包创建时所能访问的所有局部变量。

在局部作用域中定义局部变量、内部函数,内部函数的作用域链持有对局部变量对引用。

 

编程语言中(比如 Java)支持将方法声明为私有的,而 JavaScript 没有这种原生支持,但我们可以使用闭包来模拟私有方法。

 

 

二 使用块级作用域

 

{
    let fruit = 'apple';
    function eat(){
        console.log(fruit);
    }
    window.eat = eat;
}

console.log('fruit' in window,'eat' in window); // false true
eat(); // apple

 

 

二 使用立即执行函数

 

// 函数
let drink = (function(){
    let coffee = 'nestle';
    return function(){
        console.log(coffee);
    }
})();

console.log('coffee' in window,'drink' in window); // false false
drink(); // nestle

 

三 使用普通函数

 

// 函数
function _drink(){
    let coffee = 'nestle';
    return function(){
        console.log(coffee);
    }
};

let drink = _drink();

console.log('coffee' in window,'drink' in window); // false false
drink(); // nestle

 

推荐阅读