Javascript 中的变量

var a;
console.log("The value of a is " + a); // The value of a is undefined

console.log("The value of b is " + b); // The value of b is undefined
var b = 3;

console.log("The value of c is " + c); // Uncaught ReferenceError: c is not defined

let x;
console.log("The value of x is " + x); // The value of x is undefined

console.log("The value of y is " + y); //Uncaught ReferenceError
let y;

变量提升,使用var 时,例子中的b 会被提升,但值仍未undefined 。 使用let 可以避免提示,打印 y 时将报错。

/**
 * Example 1
 */
console.log(x === undefined); // true
var x = 3;

/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";
 
(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

注意上面的自调用函数中,myvar 是指local 域中,它覆盖了global域中的myvar =“my value"; 所以myvar 被提示,值为undefined。

 

/* Function declaration */

foo(); // "bar"

function foo() {
  console.log("bar");
}


/* Function expression */

baz(); // TypeError: baz is not a function

var baz = function() {
  console.log("bar2");
};

函数声明将会被提升,而函数表达式将不会提升,所以baz()将报错

 

posted @ 2016-11-09 16:23  没离开过  阅读(146)  评论(0编辑  收藏  举报