未加星标

Block Scope and Hoisting An Exercise in Rubber Ducking

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

This is a follow up to‘Intro to Scope’, previously posted here at CrookedCode. It’s part of ourrubber ducking series, where we’re attempting to work through some of the more difficult parts of javascript using Kyle Simpson’s book series, You Don’t Know JS , as a guide.

If you want to know more about the project, check outthis post. If you’re thinking to yourself “Where does this guy get off thinking he can explain this stuff better than Kyle Simpson?”, check out the disclaimerhere. Otherwise, read on…

As the title suggests, this post will cover block scope versus function scope, particularly astheypertains to var , let and const . I’d like to start with the concept of hoisting, however, as I think it’ll help understand the rest of the article.

WTFis Hoisting? (And Do I need a boat to do it?)

Consider the following:

function hoist(a) { hoisted = a; console.log(hoisted); var hoisted; } hoist("Will this get logged?");

The question here is will “Will this get logged?” actually get logged to the console even though hoisted is declared after it A) has a value assigned to it and B) gets logged.

The answer is yes, “Will this get logged?” is logged to the console.

You’ve also probably seen examples of functions getting invoked before they’re even declared. Have you wondered why that works too…

Something like:

var b = printYourDogsName('Henry'); console.log(b); function printYourDogsName(name) { return name; }

The above snippet will log ‘Henry’ to the console.

Both of the above examples work because of hoisting. As we mentioned in the previous article,JavaScript is a compiled language. Part of the compilation step is finding all the declarations (variables and functions) and associate them with the appropriate scope.

This part actually occurs first, before the code is executed. Therefore any function or variable declared in a given scope will be available throughout that scope.

In the first example above, var hoisted would have been ‘hoisted’ to the top of scope within the hoist() function. So whenthe JS engine comes across hoisted = a and searches for a variable called hoisted in the lexical scope within the hoist() function, it’ll find it!

One more note on hoisting…

Don’t confuse declaring a variable with assigning a value to a variable, even if that happens in the same line of code.

var name = 'Henry'; is seen as two statements by the JS engine, var name; and name = 'Henry'; . The declaration is hoisted, the assignment is not…

If you think this is just semantics, consider the following:

function printYourDogsName(name) { console.log(a); var a = name; } printYourDogsName('Henry');

Someone with a tenuous grasp on scope might look at this snippet of code and think there are a couple possibilities…

“That’ll probably be a ReferenceError because a is declared after it’s logged..”

Nope…

or if they’ve heard of hoisting….

“Maybe it’ll print ‘Henry’ to the console because a is hoisted within the printYourDogsName function”

Nope again…

The actual answer is that the snippet logs undefined . If you think back to the last article, undefined (as opposed to ReferenceError ) means that the JS engine found the variable a (because it was hoisted), but a was undefined (because the a = name assignment didn’t happen until after console.log(a) .

Ok, enough about hoisting… I think that should give us a pretty good grasp on how things work. For more detail please refer to YDKJS.

The Complexity of Scope

I hope my previous article, along with what’s covered here, has given you a pretty good understanding of lexical scope and how it works in JavaScript. So why did Kyle Simpson feel the need to devote an entire book to scope and closures?

You know the old saying ‘You don’t know what you don’t know…”? Well, there areseveral special circumstances that are covered in ‘Scope and Closures’ that I won’t be addressing here at Crooked Code of which you should be aware.

One such concept is using scope to hide access to variables. I plan to touch upon some of this in a future article on Modules, but in the meantime, YDKJS covers it here .

You can also read about the specifics of scope as it pertains to function expressions,including Immediately Invoked Function Expressions or IIFEs, here .

The final topic you should be aware of that I won’t be covering in this article is closure. Simpson devotes an entire chapter to closure and I highly recommend reading it.

I’ve read it a couple times and my pulse still quickensa bit when someone mentions closure (I’ll be writing a rubber ducking article here on closure in the near future to solidify the concept in my own head).

Now on to Block Scope

We’ve discussed previously that JavaScript uses functions to define scope.

This was, for the most part , entirely true until ES6. Among the changes in ES6 were the keywords let and const , which provide us ways to declare variables with block scope.

The only difference between the two is const declares a constant, which can’t be changed once assigned a value.

Before we get into what block scope is, there’s a key note to remember when dealing with let and const . They are NOT hoisted within their block of scope. This means that you must declare them before you use them or it will result in a ReferenceError .

Now, what’s block scope? Simpson tells us a block is commonly a {...} pair. So think for loops, if statements, etc.. You can even create your own block of scope by enclosing codein curly brackets.

Block scope can be useful in several key ways… Consider the following:

function redundantI(num) { var i = num; for(var i = 0; i<10; i++){ //do something really important } console.log(i); } redundantI(42);

In this example, as I’m sure you can figure out by now, 10 (not 42 ) would get logged to the console. This is because i would be hoisted to the scope within the redundantI function. So when the engine comes across the var i = 0 statement in the for loop, it will already see the i variable and use that one. Now consider:

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

主题: JavaScriptJava
分页:12
转载请注明
本文标题:Block Scope and Hoisting An Exercise in Rubber Ducking
本站链接:http://www.codesec.net/view/532869.html
分享请点击:


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