Javascript闭包

Dev*_*evX 9 javascript closures

我仍然对JavaScript中的闭包概念感到困惑.我得到的结论是,闭包是内部函数在母函数返回后访问其母函数中创建的变量的能力.但我仍然困惑为什么我们必须创建内部函数来保护局部变量,如果我们可以在函数内部创建一个变量?

bry*_*mac 1

您需要使用作用域变量创建内部函数的原因是面向对象的封装。它本质上是私有变量。

变量是“封闭的”。

// constructor function
var myObject = function(message) {
    // private - scope is function level.  It's CLOSED OVER the the inner function (closure).
    //           not delcared as a JSON property so not visible externally
    var value = 0;
    // constructor returns JSON object with public methods
    // always constructed from the myObject var so it always hands back the same instance
    // of the public methods
    return {
        // nested functions have access to outer function variables.
        increment: function (inc) {
            value ++;
        },
        getValue: function() {
            return value;
        },
        // the inner function even has access to the outer function's args!
        getMessage: message
    }
};
Run Code Online (Sandbox Code Playgroud)

看返回语句。它返回公共接口 - 一些可以访问私有变量的方法,因为它们位于内部函数中。它使用 JavaScript 函数作用域变量来创建面向对象的封装。

之后我可以这样:

var obj = myObject('Hello World');
obj.increment();
obj.increment();
console.log(obj.getValue());
console.log(obj.getMessage);
// should be undefined
console.log(obj.value);
Run Code Online (Sandbox Code Playgroud)

请注意,此时消费者无权访问受保护/封装的值或消息。

现在,关键是 - 对象是可变的,因此调用者可以添加方法甚至替换方法。因此,您可能会认为有人可以添加一个公开内部结构的方法。但是,由于函数范围(闭包 - 它们已关闭),它们不能。只有嵌套函数才能访问外部函数的变量。因此,如果调用者添加一个方法来返回内部,他们将无法访问并且该方法将是未定义的。

上面的代码输出:

2
Hello World
undefined
Run Code Online (Sandbox Code Playgroud)

作为旁注,我正在使用node.js运行 javascript

这是一篇关于使用闭包的模块模式的好博客文章:

http://www.yuiblog.com/blog/2007/06/12/module-pattern/