两个个关于javascript的scope的有趣的例子

// Functions can see changes in variable values after the function is defined
var myFunction = function() {
    var foo = "hello";
    var myFn = function() {
        console.log( foo );
    };
    foo = "world";
    return myFn;
};
 
var f = myFunction();
f(); // "world"

 

// Scope insanity
// a self-executing anonymous function
(function() {
  var baz = 1;
  var bim = function() {
    alert( baz );
  };
 
  bar = function() {
    alert( baz );
  };
 
})();
 
// baz is not defined outside of the function
console.log( baz );
 
// bar is defined outside of the anonymous function
// because it wasn't declared with var; furthermore,
// because it was defined in the same scope as baz,
// it has access to baz even though other code
// outside of the function does not
bar();
 
// bim is not defined outside of the anonymous function,
// so this will result in an error
bim();

 

 

来自jquery的教学课程: http://learn.jquery.com/javascript-101/scope/

你可能感兴趣的:(JavaScript)