JavaScript中的闭包的实际用途是什么? [英] What is a practical use for a closure in JavaScript?

查看:100
本文介绍了JavaScript中的闭包的实际用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是尝试我最难以围绕JavaScript闭包的。

I'm trying my hardest to wrap my head around JavaScript closures.

通过返回一个内部函数,它可以访问在其直接父对象中定义的任何变量。

I get that by returning an inner function, it will have access to any variable defined in its immediate parent.

对我有用吗?也许我还没有得到我的头。我在网上看到的示例中的大多数都不提供任何真实世界的代码,只是模糊的示例。

Where would this be useful to me? Perhaps I haven't quite got my head around it yet. Most of the examples I have seen online don't provide any real world code, just vague examples.

有人可以告诉我一个真实世界使用闭包吗?

Can someone show me a real world use of a closure?

这是一个吗?

var warnUser = function (msg) {
    var calledCount = 0;
    return function() {
       calledCount++;
       alert(msg + '\nYou have been warned ' + calledCount + ' times.');
    };
};

var warnForTamper = warnUser('You can not tamper with our HTML.');
warnForTamper();
warnForTamper();


推荐答案

我使用闭包来做: / p>

I've used closures to do things like:

a = (function () {
    var privatefunction = function () {
        alert('hello');
    }

    return {
        publicfunction : function () {
            privatefunction();
        }
    }
})();

正如你所看到的, a 现在是一个方法 publicfunction a.publicfunction())调用 privatefunction ,它只存在于闭包内。您可以直接调用 privatefunction (即 a.privatefunction()), code> publicfunction()。

As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction, which only exists inside the closure. You can NOT call privatefunction directly (i.e. a.privatefunction() ), just publicfunction().

它是一个最小的例子,但也许你可以看到它的用法?我们使用它来强制执行公共/私有方法。

Its a minimal example but maybe you can see uses to it? We used this to enforce public/private methods.

这篇关于JavaScript中的闭包的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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