javascript - 从另一个函数内部调用私有(private)函数

标签 javascript jquery structure private public

我无法从另一个函数内部调用内部函数。我需要能够在页面加载时调用 funcA,向其传递一个元素和一些尺寸,然后将一些样式应用于传递 elem。 funcB 然后使用所述参数来正确调整元素的大小:

var funcA = function(elem, width, height) {

     //performs layout restyle
     function funcB() {
          //performs sizing 
     }

     funcB();
}

但是,问题是我需要从像这样的去抖调整大小函数中调用 funcB 。

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
var resizeFn = debounce(function() {

    funcB();

}, 10);

$(window).on('resize', resizeFn);

使 funcB 可用的最佳实践是什么?我一直在考虑返回它然后将其缓存到变量:

var funcA = function(elem, width, height) {

     //performs layout restyle
     function funcB() {
          //performs sizing 
     }

     funcB();

     return funcB
}

var scopedFuncB = funcA;

scopedFuncB();

但是有更好的方法吗?

最佳答案

I'd been considering returning it

是的,这绝对是最佳实践。因此调用者可以决定如何处理它以及调用它的时间和频率。

…and then caching it to variable

实际上没有必要。您可以直接将其传递给 debounce ,无需多言:

$(window).on('resize', debounce(funcA(elem, width, height), 10));

关于javascript - 从另一个函数内部调用私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865271/

相关文章:

javascript - 如何使 d3 饼图响应式?

javascript - 数组缩减未返回预期结果

javascript - React 切换 map 功能

jQuery 弃用通知 jqxhr.success()

c++ - 没有运算符 ">>"匹配这些操作数 操作数类型是:std::istream >> double*

javascript - iOS UIWebView 中未定义 requestAnimationFrame?

jquery - 使用Jquery解析网页的html,修改,然后重新插入网页

javascript - 更改 HTML 表格中特定列的背景颜色

c - 我无法用c语言读取另一个结构

c - 在 C 和 C++ 中使用结构