2

Why are Javascript bookmarklets wrapped in closures?
I wouldn't think someone would put an unnamed function in there for no reason.

I have read quite a few explanations on closures, but I still don't feel that i've grasped the whole concept.

Thanks guys!

Web_Designer
  • 72,308
  • 93
  • 206
  • 262

6 Answers6

2

To not contaminate the global scope by executing a function after creation.

(function(){var x=10; })()
alert(window.x) // undefined
Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42
1

This prevents variables in the bookmarklet from leaking into the page.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Two reasons:

contamination

The first is for preventing global contamination for any of the variables needed for the bookmarklet. Using a closure means that var a wont add window.a to the global context. Additionally, using a named function would add it to the global namespace. function a() {...} would add window.a.

accidental DOM recreation

The second is to avoid accidentally recreating the DOM by returning a string. Any javascript: url where a string is returned will create a brand new DOM using the contents of the string as the source.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

Because the folks who are making them are good citizens of the web :) and don't want to step over the actual page's JavaScript accidentally.

Rajat
  • 32,970
  • 17
  • 67
  • 87
0

A mixture of scope conflicts and return policy.

zzzzBov's answer in this thread covers the main issues succinctly.

Community
  • 1
  • 1
CBusBus
  • 2,321
  • 1
  • 18
  • 26
0

It's generally to avoid polluting the global namespace, it's also known as the Module Pattern as described by Ben Cherry: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Ken Struys
  • 1,789
  • 1
  • 10
  • 17