javascript关闭优点? [英] javascript closure advantages?

查看:219
本文介绍了javascript关闭优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JS中 Closures 的主要用途是什么?它只是用于公共和私有变量吗?或者有其他我错过了。我想了解闭包,真的想知道使用它的主要优点。

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.

推荐答案

我认为最好的短语总结闭包的目的是:

I think the best phrase to sum up the purpose of closures would be:

使用函数闭包可以存储数据

With a function closure you can store data in a separate scope, and share it only where necessary.

如果你想模拟私人静态变量可以在函数中定义一个类,并在闭包中定义 private static vars

If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:

(function () {
    var foo;
    foo = 0;
    function MyClass() {
        foo += 1;
    }
    MyClass.prototype = {
        howMany: function () {
            return foo;
        }
    };
    window.MyClass = MyClass;
}());

这篇关于javascript关闭优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆