【发布时间】:2015-07-04 02:34:50
【问题描述】:
我无法从另一个内部调用内部函数。我需要能够在页面加载时调用 funcA 传递它一个元素和一些尺寸,然后将一些样式应用于传递元素。 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();
但是有更好的方法吗?
【问题讨论】:
-
您如何以及在何处定义去抖动调整大小功能?
-
将其返回以形成闭包听起来是一种可行的方式。你不喜欢它什么?请向我们展示该尝试的全部代码。
-
见上,不是我不喜欢,是可行的,只是想知道有没有办法做到不污染全局命名空间
-
如果它是一个内部函数,你真的应该在外部调用它吗?如果是这样,为什么不让它成为一个外部函数呢?
-
我想你会想要
var scopedFuncB = funcA(…);(甚至可能不会从funcA中调用funcB())。
标签: javascript jquery structure private public