Function Expressions scope

2961 단어 IEOperaF#Safari

/*
 :
         In JScript the identifier in a function expression is visible in the enclosing scope because such expressions are treated as function declarations. Example: 
*/
<script> 
       var foo = function bar(b) 
       { 
           if (b == true) 
           {
                bar(); // works because bar is visible inside itself 

           }   
           else 
           { 
               document.write("hello"); 
           } 
      } 
      foo(); 
      // works because foo is a ref to Function object bar(false); 
      // should fail because bar is not visible here 
</script>
/* Output: 
            IE: prints "hellohello" 
            FF: prints “hello” followed by syntax error (bar is not defined) 
            Opera: prints “hello” followed by ReferenceError (Reference to undefined variable: bar) 
            Safari: prints “hello”
*/

/*
Note: IE treats nested function expressions containing a function name as a function declaration that is scoped to the enclosing function (applying the second bullet rule from §10.1.3 instead of case 3 of the semantics in §13. In the following example the forward reference to x gets resolved in IE, whereas we get a syntax error in FF and TypeError in Opera. Example: 
*/
<script> 
function f(x) 
{ 
    x(); 
    y = function x() 
    {
         document.write("inner called ")
     }; 
     document.write(x);
     document.write(arguments[0]); 
} 
document.write("test 4 ");
 f("param"); 
</script>
/*
       Output: 
          IE: test 4 inner called function x() {document.write("inner called ")}function x() {document.write("inner called ")}
       FF: test 4 Opera: test 4 
       Safari: test 4 
Here is another example of the same issue: 
*/
<script> 
function foo() 
{ 
        function bar() {}
        var x = function baz(z) 
       { 
           document.write("baz" + z); 
           if (z) baz(false); 
       };
        x(true); // legal;
        bar();   // legal 
        baz(true); // should be illegal, is legal 
} 
foo(); 
</script>
/* The function statement bar should add “bar” to foo‟s variable object. The function expression baz should NOT add “baz” to foo‟s variable object, but it should be in scope when baz is called, so that it can do the recursive call. 
         Output: IE: baztruebazfalsebaztruebazfalse 
                 FF: baztruebazfalse (followed by an error – baz not defined) 
                 Opera: same as FF
*/

좋은 웹페이지 즐겨찾기