重构不同范围的变量

时间:2017-02-01 20:26:19

标签: javascript

$(function () {
    var wrapper = $('.table-wrapper');
    var table = $('.multiples-table');
    var filter = $('.filter');

    //use these variables in calculations

    $('#filter').keyup(function () {
        var wrapper = $('.table-wrapper');
        var table = $('.multiples-table');
        var filter = $('.filter');

        //use the same variables in different calculations
    });
});

如何重构这些变量,所以我只需要声明一次?谢谢。

2 个答案:

答案 0 :(得分:4)

因此,这些变量已经特定于您最顶层的功能内容。因此,除非您在该函数中的某处更改它们,否则您可以直接在您的keyup函数中使用它们:

$(function () {
    var wrapper = $('.table-wrapper');
    var table = $('.multiples-table');
    var filter = $('.filter');

    //use these variables in calculations

    $('#filter').keyup(function () {
        // just use wrapper, table and filter here, as is. No need to re-declare them

        //use the same variables in different calculations
    });
});

希望这有帮助!

答案 1 :(得分:0)

你试过这个:

$(function () {
    var wrapper = $('.table-wrapper');
    var table = $('.multiples-table');
    var filter = $('.filter');

    //use these variables in calculations

    $('#filter').keyup(function () {
        let wrapper = $('.table-wrapper');
        let table = $('.multiples-table');
        let filter = $('.filter');

        //use the same variables in different calculations
    });
});