1

At the moment I am trying so write better code by paying more attention to structure & patterns. Out of interest I started to look at other people's code to see how they have structured it. One 'pattern' I came across multiple times is something like this:

function foo(a, b) {

    function bar() {
      // do something with a & b
    }

    bar();

  // event handler, e.g. resize  
  $(window).on('resize', bar);
}

$(document).ready(function () {

    foo(a, b);
});

So a function is defined and e.g. two values are passed to that function. In that function, another function is defined where something is done with the two values. That second function is then attached to an event handler (the resize event is just an example). Finally, the outer function is fired when the DOM is ready.

Why do people write their code like this, just to keep the document ready function nice and clean? Or to stop people from binding there function to another event? Maybe it has something to do with variable scope?

Also, why fires bar before the event handler is attached, is this some kind of init to set values and then only adjust them when a certain event occurs?

4

1 回答 1

1

是的,用于 DRY,图像示例:功能栏例如设置宽度或计算其他一些元素的宽度,并且立即调用他,用于计算初始宽度。但是当窗口调整大小时,您必须重新计算,以便将该函数绑定到事件调整大小。

将函数放入函数的好例子是模块模式: 链接到好的免费电子书以学习 javascript 模式

于 2013-10-07T21:32:28.217 回答