/* 官网原文: When a function is defined using a function declaration, JScript binds the function to the global scope regardless of any scope changes introduced by with clauses. */ var v = 'value 1'; var o = {v: 'value 2'}; function f1() { alert('v == ' + v); }; with (o) { function f2() { alert('v == ' + v); }; } // call with the initial values f1(); f2(); // now modify the values v = 'modified value 1'; o.v = 'modified value 2'; f1(); f2(); /* Output: IE: v == value 1 v == value 1 v == modified value 1 v == modified value 1 FF: v == value 1 v == value 2 v == modified value 1 v == modified value 2 Opera: same as IE Safari: same as FF */ /* 官网原文: Contrast the above example with the case where the function is defined as a function expression: */ var v = 'value 1'; var o = {v: 'value 2'}; var f1 = function () { alert('v == ' + v); }; with (o) { var f2 = function () { alert('v == ' + v); }; } // call with the initial values f1(); f2(); // now modify the values v = 'modified value 1'; o.v = 'modified value 2'; f1(); f2(); /* Output: IE, FF, Opera, Safari: v == value 1 v == value 2 v == modified value 1 v == modified value 2 */
// case 1 var o = false; with ({o : true}) { function f() { return o; } } document.write("FunDecl in with-smt is run time instantiated? " +f() +" (should be: true)"); document.write("<br>");
// case 2 var usebeforedeclare = (typeof fn === 'function'); if (true) { function fn() { return true; } } else { function fn() { return false; } } document.write("FunDecl in if-smt is parse time instantiated? " +usebeforedeclare +" (should be: false)\nThe correct path is taken: " +fn() +" (should be: true)"); document.write("<br>");
// case 3 BRANCH : { break BRANCH; function fnc(){} } document.write("FunDecl in labelled statement is parse time instantiated? " +(typeof fnc === 'function') +" (should be: false)"); document.write("<br>");
// case 4 while (false) function func(){} document.write("FunDecl in while-smt is parse time instantiated? " +(typeof func === 'function')+ " (should be: false)"); document.write("<br>");
// case 5 for ( ; false; ) function funct(){} document.write("FunDecl in for-smt is parse time instantiated? " +(typeof funct === 'function') +" (should be: false)"); document.write("<br>");
// case 6 for(var t in {}) function functi(){} document.write("FunDecl in for..in-smt is parse time instantiated? " +(typeof functi === 'function') +" (should be: false)"); document.write("<br>");
// case 7 try { } catch(e) { function functio(){} } document.write("FunDecl in try..catch-smt is parse time instantiated? " +(typeof functio === 'function') +" (should be: false)"); document.write("<br>");
// case 8 if (true) { function bar() { document.write("bar1"); } } else { function bar() { document.write("bar2"); } } bar(); function foo() { if (true) { function baz() { document.write("baz1"); } } else { function baz() { document.write("baz2"); } } baz(); } foo();