未加星标

Intro to Scope An Exercise in Rubber Ducking

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

As Istated previously, I’ll be writing a series of posts attempting to explain, or rubber duck , some of the more difficult topics in the You Don’t Know JS (YDKJS) series by Kyle Simpson.

Before you start screaming at me that Kyle Simpson has forgotten more about javascript than I ever knew, to which I would wholeheartedly agree, please read the following disclaimer…

Disclaimer:

I have great respect for Kyle Simpson, his method for teaching and the YDKJS series. By no means is this meant to take anything away from the work of Mr. Simpson. This series of posts is merely an attempt to supplement his series and hopefully help solidify these concepts in both your mind and mine. If you are learning to code in JavaScript, I highly encourage you to read the YDKJS series.

What is Scope?

Variables are extremely important to computer programming. They allow us to write complex and dynamic programs.

But how and where should we create variables? How and where do we store them? And, maybe most importantly, how and from what part of the program are we able to access a particular variable?

Each language has very specific rules for these questions. These rules can be thought of as Scope. Here we’ll introducethe rules of scope specific to JavaScript.

Given that scope is a fairly broad topic, with many different aspects to cover, I think it best tobreak this into multiple blog posts. The goal herewill be to introduce the topic of scope and provide a foundation that we can build upon in later discussions.

What wecover here can be found in far greater depth in the 2nd YDKJS book “Scope and Closures” .

Let’s begin by taking a step back…

JavaScript is a Compiled Language (surprise!!)

For those who have worked with more traditionally compiled languages like C++ or Java, it may come as a bit of a surprise that JavaScript is actually compiled before it runs. This misunderstanding is likely because, unlike many other languages, JavaScript is compiled just before run time rather than in an entirely different build step.

Right now you may be asking yourself why this is relevant to a discussion on Scope… That’s a great question, let me try to explain.

Simpson describes that, at a very high level, the 3 basic steps in compilation are 1) tokenizing/lexing, 2) parsing and 3) code-generation.

The tokenizing or lexing step breaks up strings of characters in your code into chunks (tokens) that are easier to understand. Next, the parsing step takes all these tokens and forms a tree of nested elements called an Abstract Syntax Tree. This tree represents the grammatical structure of the program. It is from this AST that code is generated in step 3.

Still not clear on how this relates to scope, right?

To clear this up, you must understand that JavaScript employs lexical scoping rather than dynamic scoping .

This means that the scoping for a program is determined at the time of lexing,based on where the variables fall within the blocks of scope. Therefore the author is able to control the scope at the time he is writing the program without worrying that the scopes will change at run time.

This is a key concept in understanding the behavior of scope. For more detail, please read the first 2 chapters in “Scope and Closures” .

As with most rules, there are exceptions…. Simpson discusses several ways to change lexical scoping at run time. This can be accomplished using eval() and with(), both of which he frowns upon using. I don’t plan on going over these here, but you can be read about them in Ch. 2 .

General rules and behavior of scope in JavaScript

Generally speaking, (and again, there are several exceptions to this rule, which we will likely cover in later posts) JavaScript derives its scope from functions.

What does this mean?

You can think of scope as a series of boxes contained within each other. These boxes contain the functions and variables that are declared within that function. This structure enablescontrol over how one block of scope is allowed to access another.

In JavaScript, there is a scope (or box) that contains the entire program, called global scope. Each time you create a new function, a new scope box is created. This new scope will contain any new variables or function declared within (including any parameters declared in the function definition).

And so on, and so on, as functions continue to be nested within other functions…

Mentally, you can picture scope as something like this:


Intro to Scope   An Exercise in Rubber Ducking
The numbers are included only for reference and should not be used to infer relationships between blocks.

When you reference a variable within a JS function, the current scope will be searched. If the variable is found, great, that’s what will be used. If it isn’t found, the JavaScript engine will continue to search the scope boxes incrementally outward. The first match it comes across will be used.

Let’s usethe modeldepicted above… Let’s say the function for scope #5 referenced a variable called ‘foobar’. If ‘foobar’ was not found in scope #5, the JS engine would then search scope #3. If not found in #3, it would search #2, then #1. Scopes #6 and #4 would not be searched.

What happens if the JS engine reaches the global scope and is unsuccessful in finding ‘foobar’? The answer to that depends on what you are trying to do with the variable.

LHS vs RHS References

Simpson describes two scenarios for referencing a variable. He calls them LHS (Left hand side) or RHS (Right hand side) references and they are handled differently in the case of an unsuccessful lookup.

While LHS and RHS refer to which side of the assignment operator(=) the variable is found, this shouldn’t be taken literally, as there are multiple ways to assign a value to a variable.

Rather, think of the difference as such… LHS is a lookup where we are trying to assign a new value to the variable, whereas RHS is merely looking up the value of the variable to use within your function.

Let’s look at an example:

function addOne(a) { var sum = a + 1; console.log(sum); } addOne(9);

First, let’s go through this code, find the variables and decide in which scope they reside. There are 2 distinct blocks of scope here. The global scope and the scope inside the addOne function.

There’s only 1 variable in the globalscope and it’s the function addOne . The scope nested inside the addOne function contains 2 variables, sum and a .

Now, where and how are these variables referenced?

There are 2 references toeach variable in the addOne function.

Line 1 contains an LHS lookup for a . It’s LHS because we are assigning the value of 9 to the variable a when the function is called. Then there is an RHS lookup of

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaJavaScriptC++
分页:12
转载请注明
本文标题:Intro to Scope An Exercise in Rubber Ducking
本站链接:http://www.codesec.net/view/524229.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(70)