0

Hello i started with closures few days ago and i would like to know if i am on the right path. I ve read a lots of stuff also here but i feel that i need my own example . so this is my example :

var test = {
 app: function() {
 var a = "asdasd0";
 function f() {
  document.write(a);
 }
 test.change();
 return f();
},
change: function() {
 $("body").css({
  "color": "red"
 });
 }
}
test.app();

Am i right when i am thinking that the function f(){...}; inside test.app is a closure and test.change() also in test.app is a closure? is there anything else ?

Also why test.change() works differently in a codepen(text is red) and jsfiddle(text is not red)? Is it a bad code and jsfiddle has a problem with it ?

  • possible duplicate of [Is it true that every function in JavaScript is a closure?](http://stackoverflow.com/q/30252621/1048572) – Bergi Dec 07 '15 at 20:37
  • Show us those codepen and jsfiddle pages. There is nothing wrong about your code, but the environment is different. Check whether the settings are fine. Did you load jQuery? Did you execute the script after page load? – Bergi Dec 07 '15 at 20:38

1 Answers1

0

Both functions are closures in terms of the the outer context in which "test" is defined, however, technically there is no closure inside "change" since there is no locally defined variables or functions. In "app" you have proper closures for which "a" is available for "f" and that function is private to only "app".

Also, the reason why it doesn't work the same on Codepen and JSFiddle is because you want to wrap this code for then the document is finished loading, I think JSFiddle executes your code before "load" is fire.

window.addEventListener('load', function init () {
  // Do your stuff here and see if it works in both.
});
joseeight
  • 904
  • 7
  • 10