当前位置: 代码迷 >> JavaScript >> javascript函数中变量的范畴
  详细解决方案

javascript函数中变量的范畴

热度:309   发布时间:2012-11-23 22:54:33.0
javascript函数中变量的范围

var first = 'hi there';
var first = (function() {
    console.log("first", first); // undefined
    var first = "hello world";
})();
//相当于
var first = 'hi there';
var first = (function() {
    var first;//the variable declaration moved to the top 
    console.log("first", first); // undefined
    var first = "hello world";
})();

// second test case
var second = 'hi there';
var second = (function() {
    console.log("second", second ); // "hi there"
    // here, we DO NOT declare a local "second" variable
})();

// in the second test case, we don't declare the local variable, so the console.log call refers to the global variable and the value is not "undefined"
//link:http://jsfiddle.net/pomeh/ynqBs/



  相关解决方案