Skip to content

Instantly share code, notes, and snippets.

@wilvandertuin
Last active December 17, 2015 15:08
Show Gist options
  • Save wilvandertuin/5629162 to your computer and use it in GitHub Desktop.
Save wilvandertuin/5629162 to your computer and use it in GitHub Desktop.
Closures in JS
<!doctype html>
<script>
var EenClosure = (function() {
// Private
var foo = 'bar';
var otherThing = function() {
// This contains the window object because it is the owner of this function.
console.dir(this);
};
// Everything returned is public and has access to private.
return {
bar: 'baz',
publicFoo: foo,
something: function() {
// This contains the public properties.
console.dir(this);
otherThing();
}
}
})();
console.log(EenClosure.foo);
console.log(EenClosure.bar);
console.log(EenClosure.publicFoo);
EenClosure.something();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment