Download You Don't Know JS: Scope & Closures PDF

TitleYou Don't Know JS: Scope & Closures
LanguageEnglish
File Size878.0 KB
Total Pages96
Table of Contents
                            Foreword
Preface
	Mission
	Review
	Conventions Used in This Book
	Using Code Examples
	Safari® Books Online
	How to Contact Us
1. What Is Scope?
	Compiler Theory
	Understanding Scope
		The Cast
		Back and Forth
		Compiler Speak
		Engine/Scope Conversation
		Quiz
	Nested Scope
		Building on Metaphors
	Errors
	Review
		Quiz Answers
2. Lexical Scope
	Lex-time
		Look-ups
	Cheating Lexical
		eval
		with
		Performance
	Review
3. Function Versus Block Scope
	Scope From Functions
	Hiding in Plain Scope
		Collision Avoidance
			Global namespaces
			Module management
	Functions as Scopes
		Anonymous Versus Named
		Invoking Function Expressions Immediately
	Blocks as Scopes
		with
		try/catch
		let
			Garbage collection
			let loops
		const
	Review
4. Hoisting
	Chicken or the Egg?
	The Compiler Strikes Again
	Functions First
	Review
5. Scope Closure
	Enlightenment
	Nitty Gritty
	Now I Can See
	Loops and Closure
		Block Scoping Revisited
	Modules
		Modern Modules
		Future Modules
	Review
A. Dynamic Scope
B. Polyfilling Block Scope
	Traceur
	Implicit Versus Explicit Blocks
	Performance
C. Lexical this
D. Acknowledgments
Colophon
Copyright
                        
Document Text Contents
Page 48

code is preferable over implicit or subtle code. This explicit block-scoping style
is easy to achieve and fits more naturally with how block-scoping works in other
languages:

var foo = true;

if (foo) {

{ // <-- explicit block

let bar = foo * 2;

bar = something( bar );

console.log( bar );

}

}

console.log( bar ); // ReferenceError

We can create an arbitrary block for let to bind to by simply including a { .. }
pair anywhere a statement is valid grammar. In this case, we’ve made an explicit
block inside the if statement, which may be easier as a whole block to move
around later in refactoring, without affecting the position and semantics of the
enclosing if statment.

TIP
For another way to express explicit block scopes, see Appendix B.

In Chapter 4, we will address hoisting, which talks about declarations being
taken as existing for the entire scope in which they occur.

However, declarations made with let will not hoist to the entire scope of the
block they appear in. Such declarations will not observably “exist” in the block
until the declaration statement.

{

console.log( bar ); // ReferenceError!

let bar = 2;

}

Garbage collection

Page 49

Another reason block-scoping is useful relates to closures and garbage collection
to reclaim memory. We’ll briefly illustrate here, but the closure mechanism is
explained in detail in Chapter 5.

Consider:

function process(data) {

// do something interesting

}

var someReallyBigData = { .. };

process( someReallyBigData );

var btn = document.getElementById( "my_button" );

btn.addEventListener( "click", function click(evt){

console.log("button clicked");

}, /*capturingPhase=*/false );

The click function click handler callback doesn’t need the someReallyBigData
variable at all. That means, theoretically, after process(..) runs, the big
memory-heavy data structure could be garbage collected. However, it’s quite
likely (though implementation dependent) that the JS engine will still have to
keep the structure around, since the click function has a closure over the entire
scope.

Block-scoping can address this concern, making it clearer to the engine that it
does not need to keep someReallyBigData around:

function process(data) {

// do something interesting

}

// anything declared inside this block can go away after!

{

let someReallyBigData = { .. };

process( someReallyBigData );

}

var btn = document.getElementById( "my_button" );

Page 95

Colophon
The cover font for is Interstate. The text font is Adobe
Minion Pro; the heading font is Adobe Myriad Condensed; and the code font is
Dalton Maag’s Ubuntu Mono.

Page 96

Scope and Closures
Kyle Simpson
Editor
Simon St. Laurent

Editor
Brian MacDonald

Editor
Melanie Yarbrough

Revision History

2014-03-06 First release

Copyright © 2014 Getify Solutions, Inc
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 [email protected]

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. , and related trade dress are
trademarks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products 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.



O’Reilly Media, Inc.
1005 Gravenstein Highway North Sebastopol, CA 95472

2014-03-06T19:46:31Z



http://my.safaribooksonline.com/?portal=oreilly
mailto:[email protected]

Similer Documents