Kyle Simpson
Scope and Closures
Scope and Closures
by Kyle Simpson
Copyright © 2014 Getify Solutions, Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA
95472.
O’Reilly books may be purchased for educational, business, or sales promotional use.
Online editions are also available for most titles (http://my.safaribooksonline.com). For
more information, contact our corporate/institutional sales department: 800-998-9938
or corporate@oreilly.com.
Editors: Simon St. Laurent and Brian Mac‐
Donald
Production Editor: Melanie Yarbrough
Proofreader: Linley Dolby
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Rebecca Demarest
March 2014: First Edition
Revision History for the First Edition:
2014-03-06: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449335588 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarks of O’Reilly Media, Inc. You Don’t Know JavaScript: Scope and Closures,
and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their prod‐
ucts are claimed as trademarks. Where those designations appear in this book, and
O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed
in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher
and author assume no responsibility for errors or omissions, or for damages resulting
from the use of the information contained herein.
ISBN: 978-1-449-33558-8
[LSI]
Table of Contents
Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
1.
What Is Scope?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Compiler Theory 1
Understanding Scope 3
Nested Scope 8
Errors 10
Review 11
2.
Lexical Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Lex-time 13
Cheating Lexical 16
Review 21
3.
Function Versus Block Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Scope From Functions 23
Hiding in Plain Scope 24
Functions as Scopes 28
Blocks as Scopes 33
Review 39
4.
Hoisting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Chicken or the Egg? 41
The Compiler Strikes Again 42
Functions First 44
iii