我无法从另一个函数内部调用内部函数。我需要能够在页面加载时调用 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/