0

I was reading an expemple of javascript closure. And there is one thing I don't understand.

Here is the exemple:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

Here is the full exemple: Fidle Exemple

What I understand, Is when you click on the element size-12 for ex, you will execute the anonymous function which change the size to 12.

What I don't understand, is if you change the code this way:

function makeSizer(size) {

    document.body.style.fontSize = size + 'px';

}

and call makeSizer(12) instead of size12 on click event, it doesn't work.

Ok I get this is what make closure interesting, but why my modification does not work ?

Regard, Charles.

Charles
  • 25
  • 4
  • What "does not work" exactly mean? Show the complete "not working" example and explain what outcome you expect from it. – zerkms Jul 07 '17 at 06:42
  • Because the `onclick` expects a `function`, when you use `makeSizer(12)` with your modification it will execute that function and set the `onclick` to whatever is returned, which in this case is `undefined`. Even with your change using `size12` wouldn't work. – George Jul 07 '17 at 06:44
  • Quentin was right my question is a duplicate and now I understand my mistake. Thanks for all your answers ! – Charles Jul 07 '17 at 11:49

1 Answers1

1

The onclick property expects a function to be passed. In your second example that is not the case as makeSizer(12) is not a function, but a function call. To get it to work you would need to wrap it inside an anonymous function like:

document.getElementById('size-12').onclick = function() {makeSizer(12);};
George
  • 6,630
  • 2
  • 29
  • 36
kalsowerus
  • 998
  • 8
  • 23