简体   繁体   English

何时在javascript中使用闭包?

[英]When to use closures in javascript?

I came across a custom filter used in angularJS where we are returning a function with a logic for custom filter. 我遇到了angularJS中使用的自定义过滤器,我们在其中返回了一个具有自定义过滤器逻辑的函数。 Here I'm not able to understand when exactly i should be using closures. 在这里,我无法理解何时应该使用闭包。 I tried to return a function with in a jquery call back function, but the control just doesn't go inside the function body, but the control goes inside the angularJS custom filter. 我试图在jquery回调函数中返回一个函数,但该控件仅不在函数体内,而该控件在angularJS自定义过滤器中。 Can someone help me understand the concept. 有人可以帮我理解这个概念吗?

AngularJS Custom filter Code, where the control goes inside the anonymous function: AngularJS自定义过滤器代码,该控件位于匿名函数内部:

app.filter('myFilter', function () {
    return function (curItem, txtSearch) {
        var results = [];
        if (txtSearch && curItem) {
            for (i = 0; i < curItem.length; i++) {
                // some logic for filter
            }
            return results;

            app.filter('myFilter', function () {
                return function (curItem, txtSearch) {
                    var results = [];
                    if (txtSearch && curItem) {
                        for (i = 0; i < curItem.length; i++) {
                            alert(curItem[i].name);
                        }
                        return results;
                    }
                }
            });}}});

Jquery function where i'm trying to pass the control with in the return anonymous function although i know like i will be able to do with in just the call back instead of using the closure. 我正在尝试在返回匿名函数中传递控件的jQuery函数,尽管我知道像我将能够在回调中使用而不是使用闭包。

$('div').on('click', function () {
    return function () {
        alert('');
    }
});

I suggest you should first understand what closures are before trying to use them. 我建议您在尝试使用闭包之前首先应了解它们是什么。 I recommend reading You-Dont-Know-JS book on GitHub for getting clarity on this topic. 我建议阅读GitHub上的You-Dont-Know-JS书籍,以使该主题更清晰。 It is very neatly and conceptually explained in this chapter. 这是非常整齐,并在概念上解释这一章。

After understanding what closures are and what are their advantages, you can yourself identify the situations where to apply it. 在了解了什么是封闭及其优点之后,您可以自己确定应用封闭的情况。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM