在循环中定义函数的最佳方法是什么?- JavaScript
What is the best way for defining functions in loops? - JavaScript
我想知道在循环中定义函数的方法更好?我总是使用第一种方式。正确吗?或者这种情况还有另一种方法?
请指导我,我在代码中经常使用第一种方式,我想知道这是不是真的?
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
function doSomething(){
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
doSomething();
$(window).resize(doSomething);
});
或
function doSomething(par1, par2, par3, par4){
var $t = par1 , $anotherEl = par2, $anotherEl2 = par3;
$t.width($anotherEl.width() + $anotherEl2.width());
// other codes ...
}
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
doSomething($t, $anotherEl, $anotherEl2, isLand);
$(window).resize(function(){
doSomething($t, $anotherEl, $anotherEl2, isLand);
});
});
感谢您的提前。
为什么要循环这样做?因为这可以在不使用如下循环的情况下完成:
function doSomething(){
$('.elements').each(function(){
// elements
var $t = $(this), $anotherEl = $t.find('.el2'), $anotherEl2 = $t.find('.el3');
// variables
var isVisble = $t.is(':visible'), isLand = $t.hasClass('.land');
// now do something with the vars here.
});
}
$(window).resize(doSomething).resize(); // <---trailing .resize() triggers on dom ready.
我看到你的方法的问题是:
- 使用循环
.each()
一次又一次地定义相同的函数,在每次迭代中执行相同的函数并绑定resize
事件。 - 第二个似乎好一点,但部分原因是
.resize
绑定。
相关文章:
- 打破承诺链的好方法是什么
- 在JavaScript中拆分日期字符串的更好方法是什么
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- 基于窗口宽度jquery的函数的替代方法是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- knex:根据结果创建数组的合适方法是什么
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- node.js是否具有'match()'方法如果是,语法是什么
- 使用Modernizr检测移动设备最可靠的方法是什么
- 确定var是否是javascript中的elementFinder对象的方法是什么
- 用javascript修复这个JSON对象字符串最干净的方法是什么
- 让会话值可用于JavaScript的好方法是什么
- 从AngularJs获取谷歌地图对象的正确方法是什么
- 使用ReactJS和Flux架构从服务器获取数据的正确方法是什么
- 列出没有 mysql 的元素的最佳方法是什么
- 克服错误的更优雅的方法是什么:需要对象说明符.当通过JXA通过Messages发送SMS时,参数没有对象说明符
- 使用较少代码隐藏和显示选择菜单内容的更好方法是什么?javascript
- 在 Javascript 中实现解耦代码/回调的正确方法是什么?
- 使用Javascript,获取元素的方法是什么,基于打开和关闭标记之间的文本