首页 > 代码库 > understanding ECMAscript 6 ---- block bindings

understanding ECMAscript 6 ---- block bindings

  Traditionally, the way variable declarations work has been one tricky part of programming in javascript. In most C-based languages, variables(more formally known as bindings, as a name is bound to a value inside a scope) are created at the spot where the declaration occurs. In JavaScript, however, this is not the case. Where your variables are actually created depends on how you declare them, and ECMAScript 6 offers options to make controlling scope easier. This chapter demonstrates why classic var declarations can be confusing, introduces block-level bindings in ECMAScript 6 and then offers some best practices for using them.

 

var Declarations and Hoisting 

  Variable declarations using var are treated as if they are at the top of the function(or in the global scope, if decalred outside of a function ) regardless of where the actual declartion occurs; this is called hoisting. For a demonstration of what hoisting does, consider the following function definition.

function getValue(condition){
		
	if(condition){
		var value = "http://www.mamicode.com/blue";
		return value;
	}else {
		return null; 
	}
}

 

    If you are unfamiliar with Javascript, you might expect the variable value to be created only if condition evaluates to true. In fact, the variable value is created regardless. Behind the scenes, the JavaScript engine changes the getValue function to look like this:

function getValue(condition){
  var value;   if(condition){
     value = "http://www.mamicode.com/blue"; return value;   }else { return null;   } }

  

  The declaration of value is hoisted to the top and the initialization remains in the same spot. That means the variable  value is still accessilble from the else clause. If accessed from the else clause, the variable would just have a value of undefined because it has not been initialized in the else block. 

  It often takes new JavaScript developers some time to get used to declaration hoistiong, and misunderstanding this unique behavior can end up causing bugs. For this reason, ECMAScript 6 introduces block-level scoping options to give developers more control overra variable‘s life cycle.

 

   在JS 编程中,变量声明起作用的方式一直是难处理的一部分。在大部分类C语言中,我们在哪里声明变量,变量就会在哪里创建。然而,在JS中,情况确不一样。

 

 

 

 

 

    

understanding ECMAscript 6 ---- block bindings