Lexical versus Dynamic Binding of Variables

Elisp supports a mixture of dynamic and lexical binding.
For a simple example illustrating the effect of a lexical binding header; download, load, and compare the code and output of the following two files.
example-sans-lexical-header.el, example-with-lexical-header.el

Make Lexical Binding the Default

For historical reasons, elisp sources files default to dynamic binding.

Fortunately the default binding can be changed to lexical binding. Note that global variables defined via defvar are still dynamically bound, so you can have the best of both worlds.

The buffer-local variable lexical-binding controls which form of binding is used by default.
The "file local variable" mechanism (described in the info pages "Specifying File Variables" node) provides a useful way to set this variable.
In a nutshell, just add ;; -*- lexical-binding: t -*- to the first line (also known as the variable property line) of your source file.

Caveats

Note that simply editing the variable propery line will not update the value of variable lexical-binding, nor will calling the command load-file.
Instead you need to use find-alternate-file, or close the buffer and reopen the file in a new one.

Also be aware that emacs will not complain if the header line is malformed.
For example, if your header looks like: ;; -*- lexical-binding: t *- you will not get an error, nor lexical binding!

Finally, note that setting lexical binding as the default needs to be done separately for each source file.

Easy Way

There is a convenient command elisp-enable-lexical-binding, which edits the variable property line and resets lexical-binding for you.