日期:2014-05-16 浏览次数:20337 次
一.Global
myglobal = "hello"; // antipattern console.log(myglobal); // "hello" console.log(window.myglobal); // "hello" console.log(window["myglobal"]); // "hello" console.log(this.myglobal); // "hello", 全局域中的this = window.??
// antipattern, do not use function foo() { var a = b = 0; // ... }?
var a = (b = 0);?
function foo() { var a, b; // ... a = b = 0; // both local }?
// define three globals var global_var = 1; global_novar = 2; // antipattern (function () { global_fromfunc = 3; // antipattern }()); // attempt to delete delete global_var; // false delete global_novar; // true delete global_fromfunc; // true // test the deletion typeof global_var; // "number" typeof global_novar; // "undefined" typeof global_fromfunc; // "undefined"?? ?In ES5 strict mode, assignments to undeclared variables (such as the two antipatterns in the preceding snippet) will throw an error.
// antipattern myname = "global"; // global variable function func() { alert(myname); // "undefined" var myname = "local"; alert(myname); // "local" } func();?? ?In this example, you might expect that the first alert() will prompt “global” and the?second will prompt “local.” It’s a reasonable expectation because, at the time of the?first alert, myname was not declared and therefore the function should probably “see”?the global myname. But that’s not how it works. The first alert will say “undefined”?because myname is considered declared as a local variable to the function. (Although the?declaration comes after.) All the variable declarations get hoisted to the top of the?function. Therefore to avoid this type of confusion, it’s best to declare upfront all variables?you intend to use.?The preceding code snippet will behave as if it were implemented like so:
myname2 = "global"; // global variable function func_fixed() { var